koishi-plugin-lutu 1.0.0

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.
Files changed (62) hide show
  1. package/lib/api/evmOpenApi.d.ts +33 -0
  2. package/lib/api/evmOpenApi.js +114 -0
  3. package/lib/api/truckersMpApi.d.ts +34 -0
  4. package/lib/api/truckersMpApi.js +133 -0
  5. package/lib/api/truckersMpMapApi.d.ts +6 -0
  6. package/lib/api/truckersMpMapApi.js +25 -0
  7. package/lib/api/truckyAppApi.d.ts +12 -0
  8. package/lib/api/truckyAppApi.js +48 -0
  9. package/lib/command/ets-app/queryPoint.js +74 -0
  10. package/lib/command/ets-app/resetPassword.js +111 -0
  11. package/lib/command/tmpActivityService.js +603 -0
  12. package/lib/command/tmpBind.d.ts +2 -0
  13. package/lib/command/tmpBind.js +18 -0
  14. package/lib/command/tmpDlcMap.d.ts +3 -0
  15. package/lib/command/tmpDlcMap.js +33 -0
  16. package/lib/command/tmpMileageRanking.d.ts +3 -0
  17. package/lib/command/tmpMileageRanking.js +55 -0
  18. package/lib/command/tmpPosition.d.ts +3 -0
  19. package/lib/command/tmpPosition.js +107 -0
  20. package/lib/command/tmpQuery/tmpQuery.d.ts +2 -0
  21. package/lib/command/tmpQuery/tmpQuery.js +12 -0
  22. package/lib/command/tmpQuery/tmpQueryImg.d.ts +3 -0
  23. package/lib/command/tmpQuery/tmpQueryImg.js +103 -0
  24. package/lib/command/tmpQuery/tmpQueryText.d.ts +2 -0
  25. package/lib/command/tmpQuery/tmpQueryText.js +175 -0
  26. package/lib/command/tmpServer.d.ts +2 -0
  27. package/lib/command/tmpServer.js +41 -0
  28. package/lib/command/tmpTraffic/tmpTraffic.d.ts +2 -0
  29. package/lib/command/tmpTraffic/tmpTraffic.js +15 -0
  30. package/lib/command/tmpTraffic/tmpTrafficMap.d.ts +3 -0
  31. package/lib/command/tmpTraffic/tmpTrafficMap.js +163 -0
  32. package/lib/command/tmpTraffic/tmpTrafficText.d.ts +2 -0
  33. package/lib/command/tmpTraffic/tmpTrafficText.js +60 -0
  34. package/lib/command/tmpVersion.d.ts +2 -0
  35. package/lib/command/tmpVersion.js +14 -0
  36. package/lib/command/tmpVtc.js +29 -0
  37. package/lib/database/guildBind.d.ts +15 -0
  38. package/lib/database/guildBind.js +41 -0
  39. package/lib/database/model.d.ts +2 -0
  40. package/lib/database/model.js +65 -0
  41. package/lib/database/translateCache.d.ts +14 -0
  42. package/lib/database/translateCache.js +31 -0
  43. package/lib/index.d.ts +35 -0
  44. package/lib/index.js +276 -0
  45. package/lib/resource/dlc.html +115 -0
  46. package/lib/resource/mileage-leaderboard.html +363 -0
  47. package/lib/resource/package/SEGUIEMJ.TTF +0 -0
  48. package/lib/resource/package/leaflet/heatmap.min.js +9 -0
  49. package/lib/resource/package/leaflet/leaflet-heatmap.js +246 -0
  50. package/lib/resource/package/leaflet/leaflet.min.css +1 -0
  51. package/lib/resource/package/leaflet/leaflet.min.js +1 -0
  52. package/lib/resource/position.html +223 -0
  53. package/lib/resource/query.html +363 -0
  54. package/lib/resource/traffic.html +207 -0
  55. package/lib/util/baiduTranslate.d.ts +2 -0
  56. package/lib/util/baiduTranslate.js +30 -0
  57. package/lib/util/common.d.ts +1 -0
  58. package/lib/util/common.js +5 -0
  59. package/lib/util/constant.d.ts +8 -0
  60. package/lib/util/constant.js +16 -0
  61. package/package.json +41 -0
  62. package/readme.md +143 -0
@@ -0,0 +1,603 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ActivityService = void 0;
4
+
5
+ const koishi_1 = require("koishi");
6
+
7
+ class ActivityService {
8
+ constructor(ctx, config) {
9
+ this.ctx = ctx;
10
+ this.cfg = config;
11
+ this.todayActivities = [];
12
+ this.todayTMPEvents = [];
13
+ this.sentReminders = new Set();
14
+ this.sentNoActivityNotification = false;
15
+ this.timers = [];
16
+ this.logger = this.initLogger();
17
+ }
18
+
19
+ initLogger() {
20
+ return {
21
+ debug: (message, ...args) => {
22
+ if (this.cfg.debugMode) {
23
+ this.ctx.logger.debug(`[TMP-BOT DEBUG] ${message}`, ...args);
24
+ }
25
+ },
26
+ info: (message, ...args) => {
27
+ this.ctx.logger.info(`[TMP-BOT] ${message}`, ...args);
28
+ },
29
+ warn: (message, ...args) => {
30
+ this.ctx.logger.warn(`[TMP-BOT WARN] ${message}`, ...args);
31
+ },
32
+ error: (message, ...args) => {
33
+ this.ctx.logger.error(`[TMP-BOT ERROR] ${message}`, ...args);
34
+ },
35
+ api: (message, data) => {
36
+ if (this.cfg.debug?.logApiResponses) {
37
+ this.ctx.logger.info(`[TMP-BOT API] ${message}`, data ? JSON.stringify(data, null, 2) : "");
38
+ }
39
+ },
40
+ timing: (message, data) => {
41
+ if (this.cfg.debug?.logTimingDetails) {
42
+ this.ctx.logger.info(`[TMP-BOT TIMING] ${message}`, data || "");
43
+ }
44
+ },
45
+ matching: (message, data) => {
46
+ if (this.cfg.debug?.logActivityMatching) {
47
+ this.ctx.logger.info(`[TMP-BOT MATCHING] ${message}`, data || "");
48
+ }
49
+ },
50
+ message: (message, data) => {
51
+ if (this.cfg.debug?.logMessageSending) {
52
+ this.ctx.logger.info(`[TMP-BOT MESSAGE] ${message}`, data || "");
53
+ }
54
+ }
55
+ };
56
+ }
57
+
58
+ start() {
59
+ this.setupDailyTasks();
60
+ this.registerAdminCommands();
61
+ this.ctx.on("dispose", () => this.cleanup());
62
+ }
63
+
64
+ registerAdminCommands() {
65
+ this.ctx.command("活动查询", "手动检查今日活动")
66
+ .action(async () => {
67
+ this.logger.debug("手动执行活动检查命令");
68
+ await this.updateActivityData();
69
+ return `检查完成!\n车队平台今日活动: ${this.todayActivities.length} 个\nTMP今日参与活动: ${this.todayTMPEvents.length} 个`;
70
+ });
71
+
72
+ this.ctx.command("重置数据", "手动重置今日活动数据")
73
+ .action(() => {
74
+ this.logger.debug("手动执行数据重置命令");
75
+ this.resetDailyData();
76
+ return "✅ 今日活动数据已重置完成!";
77
+ });
78
+ }
79
+
80
+ setupDailyTasks() {
81
+ const now = new Date();
82
+ const localTime = now.toLocaleString();
83
+ const localDate = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}`;
84
+ const utcDate = now.toISOString().split("T")[0];
85
+
86
+ this.logger.timing(`开始设置每日定时任务,本地时间: ${localTime}, 本地日期: ${localDate}, UTC日期: ${utcDate}`);
87
+
88
+ const resetHour = 2;
89
+ const resetMinute = 0;
90
+ const resetDelay = this.getNextTime(resetHour, resetMinute);
91
+ const resetTimer = setTimeout(() => {
92
+ this.logger.timing("执行每日数据重置");
93
+ this.resetDailyData();
94
+ const dailyResetTimer = setInterval(() => {
95
+ this.logger.timing("执行每日数据重置");
96
+ this.resetDailyData();
97
+ }, koishi_1.Time.day);
98
+ this.timers.push(dailyResetTimer);
99
+ }, resetDelay);
100
+ this.timers.push(resetTimer);
101
+ this.logger.timing(`设置数据重置定时器: ${resetHour}:${resetMinute.toString().padStart(2, "0")}, 延迟: ${resetDelay}ms`);
102
+
103
+ this.cfg.admin.checkTimes.forEach((timeStr, index) => {
104
+ const [hours, minutes] = timeStr.split(":").map(Number);
105
+ this.setupTimer(hours, minutes, async () => {
106
+ this.logger.timing(`执行定时检查任务 #${index + 1} (${timeStr})`);
107
+ await this.updateActivityData();
108
+ await this.checkActivityStatusChange();
109
+ }, `检查定时器 #${index + 1}: ${timeStr}`);
110
+ });
111
+
112
+ this.cfg.admin.sendTimes.forEach((timeStr, index) => {
113
+ const [hours, minutes] = timeStr.split(":").map(Number);
114
+ this.setupTimer(hours, minutes, async () => {
115
+ this.logger.timing(`执行定时发送任务 #${index + 1} (${timeStr})`);
116
+ await this.checkAndSendProfileReminders();
117
+ }, `发送定时器 #${index + 1}: ${timeStr}`);
118
+ });
119
+
120
+ if (this.cfg.noActivity?.enable) {
121
+ const [noActivityHours, noActivityMinutes] = this.cfg.noActivity.time.split(":").map(Number);
122
+ this.setupTimer(noActivityHours, noActivityMinutes, () => {
123
+ this.logger.timing(`执行今日无活动通知任务 (${this.cfg.noActivity.time})`);
124
+ this.checkAndSendNoActivityNotification();
125
+ }, `无活动通知定时器: ${this.cfg.noActivity.time}`);
126
+ }
127
+
128
+ const minuteTimer = setInterval(async () => {
129
+ await this.checkAndSendActivityReminders();
130
+ }, koishi_1.Time.minute);
131
+ this.timers.push(minuteTimer);
132
+ this.logger.timing("设置每分钟检查定时器");
133
+ this.logger.debug("启动时立即更新活动数据");
134
+ this.updateActivityData();
135
+ }
136
+
137
+ setupTimer(hours, minutes, callback, name) {
138
+ const delay = this.getNextTime(hours, minutes);
139
+ const timer = setTimeout(() => {
140
+ callback();
141
+ const dailyTimer = setInterval(callback, koishi_1.Time.day);
142
+ this.timers.push(dailyTimer);
143
+ }, delay);
144
+ this.timers.push(timer);
145
+ this.logger.timing(`${name}, 延迟: ${delay}ms`);
146
+ }
147
+
148
+ getNextTime(hours, minutes) {
149
+ const now = new Date();
150
+ const target = new Date(
151
+ now.getFullYear(),
152
+ now.getMonth(),
153
+ now.getDate(),
154
+ hours,
155
+ minutes,
156
+ 0,
157
+ 0
158
+ );
159
+ if (target.getTime() <= now.getTime()) {
160
+ target.setDate(target.getDate() + 1);
161
+ }
162
+ return target.getTime() - now.getTime();
163
+ }
164
+
165
+ resetDailyData() {
166
+ const now = new Date();
167
+ const localTime = now.toLocaleString();
168
+ const localDate = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}`;
169
+ const utcDate = now.toISOString().split("T")[0];
170
+
171
+ const previousActivityCount = this.todayActivities.length;
172
+ const previousTMPCount = this.todayTMPEvents.length;
173
+ const previousReminderCount = this.sentReminders.size;
174
+ const previousNoActivityNotification = this.sentNoActivityNotification;
175
+
176
+ this.logger.info(`[数据重置] 开始重置数据,本地时间: ${localTime}, 本地日期: ${localDate}, UTC日期: ${utcDate}`);
177
+ this.logger.info(`[数据重置] 重置前数据: 活动${previousActivityCount}个, TMP${previousTMPCount}个, 提醒${previousReminderCount}个, 无活动通知${previousNoActivityNotification ? "已发送" : "未发送"}`);
178
+
179
+ this.todayActivities = [];
180
+ this.todayTMPEvents = [];
181
+ this.sentReminders.clear();
182
+ this.sentNoActivityNotification = false;
183
+
184
+ this.logger.info(`[数据重置] 每日数据已重置: 活动${previousActivityCount}→0, TMP${previousTMPCount}→0, 提醒${previousReminderCount}→0, 无活动通知${previousNoActivityNotification ? "已发送" : "未发送"}→未发送`);
185
+
186
+ this.updateActivityData().then(() => {
187
+ this.logger.info(`[数据重置] 重置后数据更新完成: 活动${this.todayActivities.length}个, TMP${this.todayTMPEvents.length}个`);
188
+ }).catch(error => {
189
+ this.logger.error(`[数据重置] 重置后数据更新失败:`, error.message);
190
+ });
191
+ }
192
+
193
+ async updateActivityData() {
194
+ try {
195
+ this.logger.debug("开始更新活动数据");
196
+ const startTime = Date.now();
197
+ await Promise.all([
198
+ this.updateTodayActivities(),
199
+ this.updateTodayTMPEvents()
200
+ ]);
201
+
202
+ const duration = Date.now() - startTime;
203
+ this.logger.info(`活动数据更新完成,耗时: ${duration}ms`);
204
+ this.logger.debug(`今日活动数量: ${this.todayActivities.length}, TMP活动数量: ${this.todayTMPEvents.length}`);
205
+ } catch (error) {
206
+ this.logger.error("更新活动数据失败:", error.message);
207
+ }
208
+ }
209
+
210
+ async updateTodayActivities() {
211
+ try {
212
+ this.todayActivities = [];
213
+
214
+ const protocol = this.cfg.api.useHttps ? "https://" : "http://";
215
+ const fullUrl = `${protocol}${this.cfg.api.url}/api/activity/info/list?token=${this.cfg.api.token}&page=1&limit=50&themeName=`;
216
+ this.logger.api(`请求车队平台API: ${fullUrl.replace(this.cfg.api.token, "***")}`);
217
+
218
+ const startTime = Date.now();
219
+ const response = await this.ctx.http.get(fullUrl, { timeout: 10000 });
220
+ const duration = Date.now() - startTime;
221
+ this.logger.api(`车队平台API响应耗时: ${duration}ms, 状态码: ${response.code}`);
222
+
223
+ if (this.cfg.debug?.logApiResponses) {
224
+ this.logger.api("车队平台API响应详情:", {
225
+ code: response.code,
226
+ totalCount: response.data?.totalCount,
227
+ listCount: response.data?.list?.length
228
+ });
229
+ }
230
+
231
+ if (response.code === 0 && response.data?.list) {
232
+ const now = new Date();
233
+ const today = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}`;
234
+ this.logger.debug(`[活动更新] 当前本地日期: ${today}, UTC日期: ${new Date().toISOString().split("T")[0]}`);
235
+
236
+ const originalCount = response.data.list.length;
237
+ this.logger.debug(`[活动更新] API返回活动总数: ${originalCount}`);
238
+ if (this.cfg.debug?.debugMode && originalCount > 0) {
239
+ const activityDates = response.data.list.map(a => `${a.themeName}: ${a.startTime?.split(" ")[0]}`);
240
+ this.logger.debug(`[活动更新] 所有活动日期:`, activityDates);
241
+ }
242
+
243
+ this.todayActivities = response.data.list.filter((activity) => {
244
+ const activityDate = activity.startTime?.split(" ")[0];
245
+ const isToday = activityDate === today;
246
+ if (!isToday && this.cfg.debug?.debugMode) {
247
+ this.logger.debug(`[活动更新] 跳过非今日活动: ${activity.themeName}, 日期: ${activityDate}, 当前日期: ${today}`);
248
+ }
249
+ return isToday;
250
+ });
251
+
252
+ this.logger.info(`[活动更新] 从车队平台找到 ${this.todayActivities.length}/${originalCount} 个今日活动`);
253
+ if (this.cfg.debug?.debugMode && this.todayActivities.length > 0) {
254
+ const todayActivityNames = this.todayActivities.map(a => `${a.themeName}: ${a.startTime}`);
255
+ this.logger.debug(`[活动更新] 今日活动详情:`, todayActivityNames);
256
+ }
257
+ } else {
258
+ this.logger.error(`[活动更新] 车队平台API返回错误: ${response.msg || '未知错误'} (代码: ${response.code || '无'})`);
259
+ this.todayActivities = [];
260
+ }
261
+ } catch (error) {
262
+ this.logger.error("[活动更新] 获取车队平台活动列表失败:", error.message);
263
+ this.todayActivities = [];
264
+ }
265
+ }
266
+
267
+ async updateTodayTMPEvents() {
268
+ try {
269
+ this.todayTMPEvents = [];
270
+
271
+ if (!this.cfg.api.vtcId) {
272
+ this.logger.warn("[TMP活动更新] TMP API请求失败:未配置api.vtcId");
273
+ return;
274
+ }
275
+
276
+ const tmpApiUrl = `https://api.truckersmp.com/v2/vtc/${this.cfg.api.vtcId}/events/attending/`;
277
+ this.logger.api(`[TMP活动更新] 请求TMP API: ${tmpApiUrl}`);
278
+
279
+ const startTime = Date.now();
280
+ const response = await this.ctx.http.get(tmpApiUrl, { timeout: 10000 });
281
+ const duration = Date.now() - startTime;
282
+ this.logger.api(`[TMP活动更新] TMP API响应耗时: ${duration}ms, 错误状态: ${response.error}`);
283
+
284
+ if (!response.error && Array.isArray(response.response)) {
285
+ const now = new Date();
286
+ const today = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}`;
287
+ this.logger.debug(`[TMP活动更新] 当前本地日期: ${today}, UTC日期: ${new Date().toISOString().split("T")[0]}`);
288
+
289
+ const originalCount = response.response.length;
290
+ this.logger.debug(`[TMP活动更新] API返回活动总数: ${originalCount}`);
291
+
292
+ if (this.cfg.debug?.debugMode && originalCount > 0) {
293
+ const eventDates = response.response.map(e => `${e.name}: ${e.start_at?.split(" ")[0]}`);
294
+ this.logger.debug(`[TMP活动更新] 所有活动日期:`, eventDates);
295
+ }
296
+
297
+ this.todayTMPEvents = response.response.filter((event) => {
298
+ const eventDate = event.start_at?.split(" ")[0];
299
+ const isToday = eventDate === today;
300
+ if (!isToday && this.cfg.debug?.debugMode) {
301
+ this.logger.debug(`[TMP活动更新] 跳过非今日活动: ${event.name}, 日期: ${eventDate}, 当前日期: ${today}`);
302
+ }
303
+ return isToday;
304
+ });
305
+
306
+ this.logger.info(`[TMP活动更新] 从TMP找到 ${this.todayTMPEvents.length}/${originalCount} 个今日活动`);
307
+
308
+ if (this.cfg.debug?.debugMode && this.todayTMPEvents.length > 0) {
309
+ const todayEventNames = this.todayTMPEvents.map(e => `${e.name}: ${e.start_at}`);
310
+ this.logger.debug(`[TMP活动更新] 今日活动详情:`, todayEventNames);
311
+ }
312
+ } else {
313
+ this.logger.error(`[TMP活动更新] TMP API返回错误: ${response.message || '未知错误'}`);
314
+ }
315
+ } catch (error) {
316
+ this.logger.error("[TMP活动更新] 获取TMP活动失败:", error.message);
317
+ }
318
+ }
319
+
320
+ async checkAndSendProfileReminders() {
321
+ await this.updateActivityData();
322
+
323
+ if (this.todayActivities.length === 0) {
324
+ this.logger.debug("今日没有活动,跳过档位检查");
325
+ return;
326
+ }
327
+
328
+ this.logger.debug(`开始检查 ${this.todayActivities.length} 个活动的档位状态`);
329
+
330
+ for (const activity of this.todayActivities) {
331
+ const hasProfile = !!activity.profileFile;
332
+ const message = hasProfile ? this.cfg.messages.profileUploaded : this.cfg.messages.profileNotUploaded;
333
+ const fullMessage = `活动 "${activity.themeName || '未知活动'}" - ${message}`;
334
+ this.logger.message(`活动档位检查: "${activity.themeName || '未知活动'}" - ${hasProfile ? "已上传" : "未上传"}`);
335
+
336
+ for (const groupId of this.cfg.admin.groups) {
337
+ try {
338
+ await this.sendToGroup(groupId, fullMessage, "管理群组");
339
+ this.logger.message(`已发送档位提醒到管理群组 ${groupId}: ${activity.themeName || '未知活动'}`);
340
+ } catch (error) {
341
+ this.logger.error(`发送消息到管理群组 ${groupId} 失败:`, error.message);
342
+ }
343
+ }
344
+ }
345
+ }
346
+
347
+ async checkAndSendNoActivityNotification(manualTest = false) {
348
+ if (!manualTest && this.sentNoActivityNotification) {
349
+ this.logger.debug("今日已发送过无活动通知,跳过");
350
+ return;
351
+ }
352
+
353
+ if (this.todayActivities.length > 0 || this.todayTMPEvents.length > 0) {
354
+ this.logger.debug(`今日有活动(车队平台: ${this.todayActivities.length}个, TMP: ${this.todayTMPEvents.length}个),不发送无活动通知`);
355
+ return;
356
+ }
357
+
358
+ this.logger.info(`${manualTest ? "手动测试" : "自动"}今日无活动,发送通知到管理群`);
359
+
360
+ for (const groupId of this.cfg.admin.groups) {
361
+ try {
362
+ await this.sendToGroup(groupId, this.cfg.noActivity.message, "管理群组");
363
+ this.logger.message(`已发送无活动通知到管理群组 ${groupId}`);
364
+ } catch (error) {
365
+ this.logger.error(`发送无活动通知到管理群组 ${groupId} 失败:`, error.message);
366
+ }
367
+ }
368
+
369
+ if (!manualTest) {
370
+ this.sentNoActivityNotification = true;
371
+ this.logger.debug("已标记今日无活动通知为已发送");
372
+ }
373
+ }
374
+
375
+ async checkActivityStatusChange() {
376
+ await this.updateActivityData();
377
+ if (this.sentNoActivityNotification && (this.todayActivities.length > 0 || this.todayTMPEvents.length > 0)) {
378
+ this.logger.info(`检测到活动状态变化:之前无活动,现在有活动(车队平台: ${this.todayActivities.length}个, TMP: ${this.todayTMPEvents.length}个)`);
379
+ this.sentNoActivityNotification = false;
380
+ await this.checkAndSendProfileReminders();
381
+ }
382
+ }
383
+
384
+ async checkAndSendActivityReminders() {
385
+ const now = new Date();
386
+ const today = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}`;
387
+ const todayUTC = now.toISOString().split("T")[0];
388
+ let remindersSent = 0;
389
+ this.logger.debug(`检查 ${this.todayActivities.length} 个活动的提醒时间,当前本地日期: ${today}, UTC日期: ${todayUTC}`);
390
+
391
+ if (this.cfg.mainGroup.groups.length === 0) {
392
+ this.logger.warn(`未配置主群组ID (mainGroup.groups为空),活动提醒将无法发送`);
393
+ } else {
394
+ this.logger.debug(`已配置 ${this.cfg.mainGroup.groups.length} 个主群组: ${this.cfg.mainGroup.groups.join(', ')}`);
395
+ }
396
+
397
+ for (const activity of this.todayActivities) {
398
+ try {
399
+ const activityDate = activity.startTime?.split(" ")[0];
400
+ if (activityDate !== today) {
401
+ this.logger.debug(`跳过非今日活动 "${activity.themeName}",活动日期: ${activityDate},当前本地日期: ${today}`);
402
+ continue;
403
+ }
404
+
405
+ const activityStartTime = new Date(activity.startTime);
406
+ if (isNaN(activityStartTime.getTime())) {
407
+ this.logger.warn(`活动 "${activity.themeName}" 开始时间格式错误,跳过提醒`);
408
+ continue;
409
+ }
410
+
411
+ const timeDiff = activityStartTime.getTime() - now.getTime();
412
+ const totalSecondsLeft = Math.floor(timeDiff / 1000);
413
+ const minutesLeft = Math.floor(totalSecondsLeft / 60);
414
+ const secondsLeft = totalSecondsLeft % 60;
415
+ this.logger.debug(`活动 "${activity.themeName}" 剩余时间: ${minutesLeft} 分 ${secondsLeft} 秒`);
416
+ this.logger.debug(`活动 "${activity.themeName}" 时间检查: totalSecondsLeft=${totalSecondsLeft}, 触发条件: -300 <= ${totalSecondsLeft} <= 0`);
417
+
418
+ if (totalSecondsLeft >= -300 && totalSecondsLeft <= 0) {
419
+ const startReminderKey = `${activity.id}_started`;
420
+ if (!this.sentReminders.has(startReminderKey)) {
421
+ this.logger.info(`触发活动开始提醒: ${activity.themeName}`);
422
+ await this.sendActivityStartReminder(activity);
423
+ this.sentReminders.add(startReminderKey);
424
+ remindersSent++;
425
+ } else {
426
+ this.logger.debug(`活动 "${activity.themeName}" 开始提醒已发送过,跳过`);
427
+ }
428
+ } else {
429
+ this.logger.debug(`活动 "${activity.themeName}" 未满足开始提醒条件,当前剩余 ${totalSecondsLeft} 秒`);
430
+ }
431
+
432
+ if (totalSecondsLeft < 0) continue;
433
+ for (const reminderTime of this.cfg.mainGroup.activityReminderTimes) {
434
+ const reminderTimeSeconds = reminderTime * 60;
435
+ this.logger.debug(`活动 "${activity.themeName}" ${reminderTime}分钟前提醒检查: totalSecondsLeft=${totalSecondsLeft}, reminderTimeSeconds=${reminderTimeSeconds}, 条件: ${reminderTimeSeconds - 60} <= ${totalSecondsLeft} <= ${reminderTimeSeconds}`);
436
+ if (totalSecondsLeft <= reminderTimeSeconds && totalSecondsLeft > reminderTimeSeconds - 60) {
437
+ const reminderKey = `${activity.id}_${reminderTime}`;
438
+ if (!this.sentReminders.has(reminderKey)) {
439
+ this.logger.info(`触发活动前提醒: ${activity.themeName} - ${reminderTime} 分钟前`);
440
+ await this.sendActivityReminder(activity, reminderTime);
441
+ this.sentReminders.add(reminderKey);
442
+ remindersSent++;
443
+ } else {
444
+ this.logger.debug(`活动 "${activity.themeName}" ${reminderTime}分钟前提醒已发送过,跳过`);
445
+ }
446
+ }
447
+ }
448
+ } catch (error) {
449
+ this.logger.error(`处理活动 "${activity.themeName}" 提醒失败:`, error.message);
450
+ }
451
+ }
452
+
453
+ if (remindersSent > 0) {
454
+ this.logger.info(`本轮发送了 ${remindersSent} 个活动提醒`);
455
+ } else {
456
+ this.logger.debug(`本轮未发送任何活动提醒`);
457
+ }
458
+ }
459
+
460
+ createActivityReplacements(activity, tmpEvent, minutesLeft) {
461
+ const replacements = {
462
+ name: activity.themeName || '未知活动',
463
+ distance: activity.distance?.toString() || '未知'
464
+ };
465
+
466
+ if (minutesLeft !== undefined) {
467
+ replacements.timeLeft = minutesLeft.toString();
468
+ }
469
+
470
+ if (this.cfg.dataSource.serverSource === "tmp" && tmpEvent) {
471
+ replacements.server = tmpEvent.server?.name || '未知服务器';
472
+ } else {
473
+ replacements.server = activity.serverName || '未知服务器';
474
+ }
475
+
476
+ if (this.cfg.dataSource.startPointSource === "tmp" && tmpEvent) {
477
+ replacements.startingPoint = `${tmpEvent.departure?.location || ''} - ${tmpEvent.departure?.city || ''}`.trim() || '未知起点';
478
+ } else {
479
+ replacements.startingPoint = activity.startingPoint || '未知起点';
480
+ }
481
+
482
+ if (this.cfg.dataSource.endPointSource === "tmp" && tmpEvent) {
483
+ replacements.terminalPoint = `${tmpEvent.arrive?.location || ''} - ${tmpEvent.arrive?.city || ''}`.trim() || '未知终点';
484
+ } else {
485
+ replacements.terminalPoint = activity.terminalPoint || '未知终点';
486
+ }
487
+
488
+ if (this.cfg.dataSource.showBanner && tmpEvent && tmpEvent.banner) {
489
+ replacements.banner = tmpEvent.banner;
490
+ } else {
491
+ replacements.banner = "无";
492
+ }
493
+
494
+ return replacements;
495
+ }
496
+
497
+ async sendActivityStartReminder(activity) {
498
+ try {
499
+ const tmpEvent = this.todayTMPEvents.find(
500
+ (event) => event.name.includes(activity.themeName) || activity.themeName.includes(event.name)
501
+ );
502
+ this.logger.matching(`活动匹配: "${activity.themeName}" - 找到TMP匹配: ${!!tmpEvent}`);
503
+
504
+ const replacements = this.createActivityReplacements(activity, tmpEvent);
505
+
506
+ let message = this.cfg.mainGroup.activityStartReminderMessage;
507
+ for (const [key, value] of Object.entries(replacements)) {
508
+ message = message.replace(new RegExp(`{${key}}`, "g"), value);
509
+ }
510
+
511
+ if (!this.cfg.dataSource.showBanner) {
512
+ message = message.replace(/活动横幅:.*?\n?/, "");
513
+ }
514
+
515
+ message = message.replace(/\\n/g, "\n").trim();
516
+ const fullMessage = `@全体成员\n${message}`;
517
+
518
+ await this.sendToMainGroups(fullMessage, activity.themeName, "开始提醒");
519
+ } catch (error) {
520
+ this.logger.error(`发送活动开始提醒失败:`, error.message);
521
+ }
522
+ }
523
+
524
+ async sendActivityReminder(activity, minutesLeft) {
525
+ try {
526
+ const tmpEvent = this.todayTMPEvents.find(
527
+ (event) => event.name.includes(activity.themeName) || activity.themeName.includes(event.name)
528
+ );
529
+ this.logger.matching(`活动匹配: "${activity.themeName}" - 找到TMP匹配: ${!!tmpEvent}`);
530
+
531
+ const replacements = this.createActivityReplacements(activity, tmpEvent, minutesLeft);
532
+
533
+ let message = this.cfg.mainGroup.activityReminderMessage;
534
+ for (const [key, value] of Object.entries(replacements)) {
535
+ message = message.replace(new RegExp(`{${key}}`, "g"), value);
536
+ }
537
+
538
+ if (!this.cfg.dataSource.showBanner) {
539
+ message = message.replace(/活动横幅:.*?\n?/, "");
540
+ }
541
+
542
+ message = message.replace(/\\n/g, "\n").trim();
543
+ const fullMessage = `@全体成员\n${message}`;
544
+
545
+ await this.sendToMainGroups(fullMessage, activity.themeName, `${minutesLeft}分钟前提醒`);
546
+ } catch (error) {
547
+ this.logger.error(`发送活动提醒失败:`, error.message);
548
+ }
549
+ }
550
+
551
+ async sendToMainGroups(message, activityName, reminderType) {
552
+ for (const groupId of this.cfg.mainGroup.groups) {
553
+ try {
554
+ await this.sendToGroup(groupId, message, "主群组");
555
+ this.logger.message(`已发送${reminderType}到主群组 ${groupId}: ${activityName}`);
556
+ } catch (error) {
557
+ this.logger.error(`发送${reminderType}到主群组 ${groupId} 失败:`, error.message);
558
+ }
559
+ }
560
+ }
561
+
562
+ async sendToGroup(groupId, message, groupType) {
563
+ const availableBots = this.ctx.bots.filter((bot) => {
564
+ const unsupportedPlatforms = ["mail", "telegram", "discord", "qq", "wechat-official"];
565
+ return !unsupportedPlatforms.includes(bot.platform);
566
+ });
567
+
568
+ if (availableBots.length === 0) {
569
+ throw new Error(`没有可用的聊天平台适配器(当前不支持邮件/电报/Discord/QQ/微信公众号)`);
570
+ }
571
+
572
+ let lastError = null;
573
+ this.logger.debug(`尝试通过 ${availableBots.length} 个适配器发送消息到${groupType} ${groupId}`);
574
+
575
+ for (const bot of availableBots) {
576
+ try {
577
+ await bot.sendMessage(groupId, message);
578
+ this.logger.debug(`已通过 ${bot.platform} 适配器发送消息到${groupType} ${groupId}`);
579
+ return;
580
+ } catch (error) {
581
+ lastError = error;
582
+ this.logger.warn(`通过 ${bot.platform} 适配器发送消息失败: ${error.message}`);
583
+ }
584
+ }
585
+
586
+ throw lastError || new Error(`所有适配器都无法发送消息到${groupType} ${groupId}`);
587
+ }
588
+
589
+ cleanup() {
590
+ this.logger.debug("插件卸载,开始清理资源");
591
+ this.todayActivities = [];
592
+ this.todayTMPEvents = [];
593
+ this.sentReminders.clear();
594
+ this.timers.forEach((timer) => {
595
+ clearTimeout(timer);
596
+ clearInterval(timer);
597
+ });
598
+ this.timers.length = 0;
599
+ this.logger.debug("资源清理完成");
600
+ }
601
+ }
602
+
603
+ exports.ActivityService = ActivityService;
@@ -0,0 +1,2 @@
1
+ declare function _exports(ctx: any, cfg: any, session: any, tmpId: any): Promise<string>;
2
+ export = _exports;
@@ -0,0 +1,18 @@
1
+ const guildBind = require('../database/guildBind');
2
+ const truckersMpApi = require("../api/truckersMpApi");
3
+ /**
4
+ * 绑定 TMP ID
5
+ */
6
+ module.exports = async (ctx, cfg, session, tmpId) => {
7
+ if (!tmpId || isNaN(tmpId)) {
8
+ return `请输入正确的玩家编号`;
9
+ }
10
+ // 查询玩家信息
11
+ let playerInfo = await truckersMpApi.player(ctx.http, tmpId);
12
+ if (playerInfo.error) {
13
+ return '绑定失败 (查询玩家信息失败)';
14
+ }
15
+ // 更新数据库
16
+ guildBind.saveOrUpdate(ctx.database, session.platform, session.userId, tmpId);
17
+ return `绑定成功 ( ${playerInfo.data.name} )`;
18
+ };
@@ -0,0 +1,3 @@
1
+ declare function _exports(ctx: any, session: any): Promise<segment | "未启用 Puppeteer 功能" | "渲染异常,请重试">;
2
+ export = _exports;
3
+ import { segment } from "@koishijs/core";
@@ -0,0 +1,33 @@
1
+ const { segment } = require('koishi');
2
+ const { resolve } = require('path');
3
+ const common = require('../util/common');
4
+ const evmOpenApi = require('../api/evmOpenApi');
5
+ module.exports = async (ctx, session) => {
6
+ if (!ctx.puppeteer) {
7
+ return '未启用 Puppeteer 功能';
8
+ }
9
+ // 查询DLC数据
10
+ let dlcData = await evmOpenApi.dlcList(ctx.http, 1);
11
+ let page;
12
+ try {
13
+ page = await ctx.puppeteer.page();
14
+ await page.setViewport({ width: 1000, height: 1000 });
15
+ await page.goto(`file:///${resolve(__dirname, '../resource/dlc.html')}`);
16
+ await page.evaluate(`setData(${JSON.stringify(dlcData.data)})`);
17
+ await page.waitForNetworkIdle();
18
+ await common.sleep(500);
19
+ const element = await page.$("#dlc-info-container");
20
+ return (segment.image(await element.screenshot({
21
+ encoding: "binary"
22
+ }), "image/jpg"));
23
+ }
24
+ catch (e) {
25
+ console.info(e);
26
+ return '渲染异常,请重试';
27
+ }
28
+ finally {
29
+ if (page) {
30
+ await page.close();
31
+ }
32
+ }
33
+ };
@@ -0,0 +1,3 @@
1
+ declare function _exports(ctx: any, session: any, rankingType: any): Promise<segment | "未启用 Puppeteer 功能" | "渲染异常,请重试" | "查询排行榜信息失败" | "暂无数据">;
2
+ export = _exports;
3
+ import { segment } from "@koishijs/core";