-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathworker.js
More file actions
2114 lines (1962 loc) · 70.5 KB
/
worker.js
File metadata and controls
2114 lines (1962 loc) · 70.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// === 配置变量(从 env 中获取)===
let TOKEN = null
let WEBHOOK = '/endpoint'
let SECRET = null
let ADMIN_UID = null
let ADMIN_GROUP_ID = null
let WELCOME_MESSAGE = '欢迎使用机器人'
let MESSAGE_INTERVAL = 1
let ENABLE_VERIFICATION = false
let VERIFICATION_MAX_ATTEMPTS = 10
// 初始化配置变量
function initConfig(env) {
TOKEN = env.ENV_BOT_TOKEN
SECRET = env.ENV_BOT_SECRET
ADMIN_UID = env.ENV_ADMIN_UID
ADMIN_GROUP_ID = env.ENV_ADMIN_GROUP_ID
WELCOME_MESSAGE = env.ENV_WELCOME_MESSAGE || '欢迎使用机器人'
MESSAGE_INTERVAL = env.ENV_MESSAGE_INTERVAL ? parseInt(env.ENV_MESSAGE_INTERVAL) || 1 : 1
ENABLE_VERIFICATION = (env.ENV_ENABLE_VERIFICATION || '').toLowerCase() === 'true'
VERIFICATION_MAX_ATTEMPTS = env.ENV_VERIFICATION_MAX_ATTEMPTS ? parseInt(env.ENV_VERIFICATION_MAX_ATTEMPTS) || 10 : 10
}
/**
* Telegram API 请求封装
*/
function apiUrl(methodName, params = null) {
let query = ''
if (params) {
query = '?' + new URLSearchParams(params).toString()
}
return `https://api.telegram.org/bot${TOKEN}/${methodName}${query}`
}
function requestTelegram(methodName, body, params = null) {
return fetch(apiUrl(methodName, params), body)
.then(r => r.json())
}
function makeReqBody(body) {
return {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(body)
}
}
function sendMessage(msg = {}) {
return requestTelegram('sendMessage', makeReqBody(msg))
}
function copyMessage(msg = {}) {
return requestTelegram('copyMessage', makeReqBody(msg))
}
function editMessage(msg = {}) {
return requestTelegram('editMessageText', makeReqBody(msg))
}
function editMessageCaption(msg = {}) {
return requestTelegram('editMessageCaption', makeReqBody(msg))
}
function deleteMessage(chat_id, message_id) {
return requestTelegram('deleteMessage', makeReqBody({
chat_id: chat_id,
message_id: message_id
}))
}
function deleteMessages(chat_id, message_ids) {
return requestTelegram('deleteMessages', makeReqBody({
chat_id: chat_id,
message_ids: message_ids
}))
}
function createForumTopic(chat_id, name) {
return requestTelegram('createForumTopic', makeReqBody({
chat_id: chat_id,
name: name
}))
}
function deleteForumTopic(chat_id, message_thread_id) {
return requestTelegram('deleteForumTopic', makeReqBody({
chat_id: chat_id,
message_thread_id: message_thread_id
}))
}
function getUserProfilePhotos(user_id, limit = 1) {
return requestTelegram('getUserProfilePhotos', null, {
user_id: user_id,
limit: limit
})
}
function sendPhoto(msg = {}) {
return requestTelegram('sendPhoto', makeReqBody(msg))
}
/**
* 设置消息 Reaction(用于双向同步 emoji reaction)
*/
function setMessageReaction(msg = {}) {
return requestTelegram('setMessageReaction', makeReqBody(msg))
}
/**
* 验证码缓存管理(使用 Cache API)
*/
class VerificationCache {
constructor() {
this.cacheName = 'verification-cache'
}
// 生成缓存键对应的 URL
_getCacheUrl(user_id, key) {
return `https://internal.cache/${user_id}/${key}`
}
// 获取验证码数据
async getVerification(user_id, key) {
try {
const cache = await caches.open(this.cacheName)
const cacheUrl = this._getCacheUrl(user_id, key)
const response = await cache.match(cacheUrl)
if (!response) {
return null
}
const data = await response.json()
return data
} catch (error) {
console.error('Error getting verification from cache:', error)
return null
}
}
// 设置验证码数据(带过期时间)
async setVerification(user_id, key, value, expirationSeconds = null) {
try {
const cache = await caches.open(this.cacheName)
const cacheUrl = this._getCacheUrl(user_id, key)
const headers = new Headers({
'Content-Type': 'application/json',
'Cache-Control': expirationSeconds
? `max-age=${expirationSeconds}`
: 'max-age=86400' // 默认24小时
})
const response = new Response(JSON.stringify(value), { headers })
await cache.put(cacheUrl, response)
return true
} catch (error) {
console.error('Error setting verification in cache:', error)
return false
}
}
// 删除验证码数据
async deleteVerification(user_id, key) {
try {
const cache = await caches.open(this.cacheName)
const cacheUrl = this._getCacheUrl(user_id, key)
await cache.delete(cacheUrl)
return true
} catch (error) {
console.error('Error deleting verification from cache:', error)
return false
}
}
}
/**
* 数据库操作封装 (使用 D1 数据库)
*/
class Database {
constructor(d1) {
this.d1 = d1
}
// 用户相关
async getUser(user_id) {
const result = await this.d1.prepare(
'SELECT * FROM users WHERE user_id = ?'
).bind(user_id.toString()).first()
if (!result) return null
return {
user_id: result.user_id,
first_name: result.first_name,
last_name: result.last_name,
username: result.username,
message_thread_id: result.message_thread_id,
created_at: result.created_at,
updated_at: result.updated_at
}
}
async setUser(user_id, userData) {
await this.d1.prepare(
`INSERT OR REPLACE INTO users
(user_id, first_name, last_name, username, message_thread_id, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?)`
).bind(
user_id.toString(),
userData.first_name || null,
userData.last_name || null,
userData.username || null,
userData.message_thread_id || null,
userData.created_at || Date.now(),
userData.updated_at || Date.now()
).run()
}
async getAllUsers() {
const result = await this.d1.prepare(
'SELECT * FROM users'
).all()
return result.results || []
}
// 消息映射相关
async getMessageMap(key) {
const result = await this.d1.prepare(
'SELECT mapped_value FROM message_mappings WHERE mapping_key = ?'
).bind(key).first()
return result?.mapped_value || null
}
async setMessageMap(key, value) {
await this.d1.prepare(
'INSERT OR REPLACE INTO message_mappings (mapping_key, mapped_value, created_at) VALUES (?, ?, ?)'
).bind(key, value || null, Date.now()).run()
}
// 话题状态相关
async getTopicStatus(thread_id) {
const result = await this.d1.prepare(
'SELECT status, updated_at FROM topic_status WHERE thread_id = ?'
).bind(thread_id).first()
return result || { status: 'opened' }
}
async setTopicStatus(thread_id, status) {
await this.d1.prepare(
'INSERT OR REPLACE INTO topic_status (thread_id, status, updated_at) VALUES (?, ?, ?)'
).bind(thread_id || null, status || 'opened', Date.now()).run()
}
// 用户状态相关(非验证码)
async getUserState(user_id, key) {
const result = await this.d1.prepare(
'SELECT state_value, expiry_time FROM user_states WHERE user_id = ? AND state_key = ?'
).bind(user_id.toString(), key).first()
if (!result) return null
// 检查是否过期
if (result.expiry_time && Date.now() > result.expiry_time) {
await this.deleteUserState(user_id, key)
return null
}
return JSON.parse(result.state_value)
}
async setUserState(user_id, key, value, expirationTtl = null) {
const expiryTime = expirationTtl ? Date.now() + (expirationTtl * 1000) : null
await this.d1.prepare(
'INSERT OR REPLACE INTO user_states (user_id, state_key, state_value, expiry_time) VALUES (?, ?, ?, ?)'
).bind(user_id.toString(), key || 'unknown', JSON.stringify(value), expiryTime).run()
}
async deleteUserState(user_id, key) {
await this.d1.prepare(
'DELETE FROM user_states WHERE user_id = ? AND state_key = ?'
).bind(user_id.toString(), key).run()
}
// 屏蔽用户相关
async isUserBlocked(user_id) {
const result = await this.d1.prepare(
'SELECT blocked FROM blocked_users WHERE user_id = ?'
).bind(user_id.toString()).first()
return result?.blocked === 1 || false
}
async blockUser(user_id, blocked = true) {
if (blocked) {
await this.d1.prepare(
'INSERT OR REPLACE INTO blocked_users (user_id, blocked, blocked_at) VALUES (?, ?, ?)'
).bind(user_id.toString(), 1, Date.now()).run()
} else {
await this.d1.prepare(
'DELETE FROM blocked_users WHERE user_id = ?'
).bind(user_id.toString()).run()
}
}
// 消息频率限制
async getLastMessageTime(user_id) {
const result = await this.d1.prepare(
'SELECT last_message_time FROM message_rates WHERE user_id = ?'
).bind(user_id.toString()).first()
return result?.last_message_time || 0
}
async setLastMessageTime(user_id, timestamp) {
await this.d1.prepare(
'INSERT OR REPLACE INTO message_rates (user_id, last_message_time) VALUES (?, ?)'
).bind(user_id.toString(), timestamp || Date.now()).run()
}
// 清理过期数据(定期调用)
async cleanupExpiredStates() {
const now = Date.now()
await this.d1.prepare(
'DELETE FROM user_states WHERE expiry_time IS NOT NULL AND expiry_time < ?'
).bind(now).run()
}
// 删除用户的所有消息映射
async deleteUserMessageMappings(user_id) {
await this.d1.prepare(
'DELETE FROM message_mappings WHERE mapping_key LIKE ?'
).bind(`u2a:${user_id}:%`).run()
}
}
let db = null
const verificationCache = new VerificationCache()
/**
* 工具函数
*/
function mentionHtml(user_id, name) {
return `<a href="tg://user?id=${user_id}">${escapeHtml(name)}</a>`
}
function escapeHtml(text) {
return text.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''')
}
function randomString(length = 6) {
const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
let result = ''
for (let i = 0; i < length; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length))
}
return result
}
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
/**
* 发送"已送达"提示(每日一次)并在3秒后撤回
*/
async function maybeSendDeliveredNotice(sender_user_id, target_chat_id, options = {}) {
const { message_thread_id = null, reply_to_message_id = null, text = '您的消息已送达\nYour message has been delivered' } = options
try {
const today = new Date().toDateString()
const stateKey = 'delivered_notice'
const lastDate = await db.getUserState(sender_user_id, stateKey)
if (lastDate === today) {
return
}
const params = { chat_id: target_chat_id, text }
if (message_thread_id) params.message_thread_id = message_thread_id
if (reply_to_message_id) params.reply_to_message_id = reply_to_message_id
const sent = await sendMessage(params)
if (sent && sent.ok) {
await db.setUserState(sender_user_id, stateKey, today)
await delay(3000)
try {
await deleteMessage(target_chat_id, sent.result.message_id)
} catch (e) {
console.error('Failed to delete delivered notice:', e)
}
}
} catch (e) {
console.error('maybeSendDeliveredNotice error:', e)
}
}
/**
* 用户数据库更新
*/
async function updateUserDb(user) {
try {
const existingUser = await db.getUser(user.id)
if (existingUser) {
// 更新现有用户信息
existingUser.first_name = user.first_name || '未知'
existingUser.last_name = user.last_name
existingUser.username = user.username
existingUser.updated_at = Date.now()
await db.setUser(user.id, existingUser)
} else {
// 创建新用户
const newUser = {
user_id: user.id,
first_name: user.first_name || '未知',
last_name: user.last_name,
username: user.username,
message_thread_id: null,
created_at: Date.now(),
updated_at: Date.now()
}
await db.setUser(user.id, newUser)
}
} catch (error) {
console.error('Error updating user database:', error)
throw error
}
}
/**
* 发送联系人卡片
*/
async function sendContactCard(chat_id, message_thread_id, user) {
console.log(`📱 sendContactCard called for user ${user.id}`)
try {
console.log(`Getting profile photos for user ${user.id}`)
const userPhotos = await getUserProfilePhotos(user.id, 1)
console.log(`Profile photos result:`, userPhotos)
if (userPhotos.ok && userPhotos.result.total_count > 0) {
const pic = userPhotos.result.photos[0][userPhotos.result.photos[0].length - 1].file_id
console.log(`Sending photo with file_id: ${pic}`)
const photoParams = {
chat_id: chat_id,
message_thread_id: message_thread_id,
photo: pic,
caption: `👤 ${user.first_name || user.id}\n\n📱 ${user.id}\n\n🔗 ${user.username ? `直接联系: @${user.username}` : `直接联系: tg://user?id=${user.id}`}`,
parse_mode: 'HTML'
}
console.log(`Sending photo with params:`, photoParams)
const result = await sendPhoto(photoParams)
console.log(`Photo send result:`, result)
if (!result.ok) {
console.error(`❌ Photo send failed:`, result)
}
return result
} else {
console.log(`No profile photo, sending text message`)
const messageParams = {
chat_id: chat_id,
message_thread_id: message_thread_id,
text: `👤 ${user.first_name || user.id}\n\n📱 ${user.id}\n\n🔗 ${user.username ? `直接联系: @${user.username}` : `直接联系: tg://user?id=${user.id}`}`,
parse_mode: 'HTML'
}
console.log(`Sending text message with params:`, messageParams)
const result = await sendMessage(messageParams)
console.log(`Text send result:`, result)
if (!result.ok) {
console.error(`❌ Text message send failed:`, result)
}
return result
}
} catch (error) {
console.error('❌ Failed to send contact card:', error)
console.error('❌ Error details:', error.stack || error)
return { ok: false, error: error.message }
}
}
/**
* 处理 /start 命令
*/
async function handleStart(message) {
const user = message.from
const user_id = user.id
const chat_id = message.chat.id
await updateUserDb(user)
if (user_id.toString() === ADMIN_UID) {
const commandList = `🤖 <b>机器人管理命令列表</b>
<b>话题管理:</b>
• /clear - 删除话题并清理数据
• /del - 删除对方与机器人的消息(回复要删除的消息),仅48小时内的消息生效,超出48小时即使提示生效也不会生效
<b>用户管理:</b>
• /block - 屏蔽用户(在话题内使用)
• /unblock - 解除屏蔽(在话题内使用或 /unblock [用户ID])
• /checkblock - 查看屏蔽列表(话题外)或检查单个用户(话题内)
<b>消息管理:</b>
• /broadcast - 群发消息(回复要群发的消息)
<b>同步功能:</b>
• ✅ Reaction emoji 双向同步已启用
<b>配置信息:</b>
• 验证功能:${ENABLE_VERIFICATION ? '已启用' : '已禁用'}
• 最大验证次数:${VERIFICATION_MAX_ATTEMPTS}次
• 消息间隔:${MESSAGE_INTERVAL}秒
✅ 机器人已激活并正常运行。`
await sendMessage({
chat_id: chat_id, // 发送到当前聊天(群组或私聊)
text: commandList,
parse_mode: 'HTML'
})
} else {
// 检查是否启用验证功能
if (ENABLE_VERIFICATION) {
// 检查用户是否已验证(使用 Cache API)
const isVerified = await verificationCache.getVerification(user_id, 'verified')
if (!isVerified) {
// 未验证,发送验证码
const challenge = generateVerificationChallenge(user_id)
await verificationCache.setVerification(user_id, 'verification', {
challenge: challenge.challenge,
answer: challenge.answer,
offset: challenge.offset,
totalAttempts: 0,
timestamp: Date.now()
}, 120) // 120秒后自动过期
await sendMessage({
chat_id: chat_id,
text: `${mentionHtml(user_id, user.first_name || user_id)},欢迎使用!\n\n🔐 请输入验证码\n\n将当前UTC+8时间的 时分(HHMM格式,仅数字)四位数字的每一位数字加上 ${challenge.offset},超过9则取个位数\n\n⏰ 请在1分钟内回复验证码,否则将失效\n\n${mentionHtml(user_id, user.first_name || user_id)}, Welcome!\n\n🔐 Please enter the verification code\n\nAdd ${challenge.offset} to each digit of current UTC+8 time in HHMM format (4 digits), if over 9, keep only the ones digit\n\n⏰ Please reply within 1 minute, or the code will expire`,
parse_mode: 'HTML'
})
return
}
}
// 已验证或未启用验证,发送欢迎消息
await sendMessage({
chat_id: chat_id,
text: `${mentionHtml(user_id, user.first_name || user_id)}:\n\n${WELCOME_MESSAGE}`,
parse_mode: 'HTML'
})
}
}
/**
* 获取UTC+8时间的HHMM四位数
*/
function getUTC8TimeDigits(offsetMinutes = 0) {
const now = new Date()
// 转换为UTC+8(加8小时)
const utc8Time = new Date(now.getTime() + (8 * 60 * 60 * 1000) + (offsetMinutes * 60 * 1000))
const hours = utc8Time.getUTCHours().toString().padStart(2, '0')
const minutes = utc8Time.getUTCMinutes().toString().padStart(2, '0')
return hours + minutes
}
/**
* 生成验证码挑战和答案(基于UTC+8时间)
*/
function generateVerificationChallenge(user_id) {
// 获取UTC+8时间的HHMM作为四位数字
const challengeDigits = getUTC8TimeDigits(0)
// 随机生成加数(1-9,避免0没有意义)
const offset = Math.floor(Math.random() * 9) + 1
// 计算正确答案
let answer = ''
for (let i = 0; i < challengeDigits.length; i++) {
const digit = parseInt(challengeDigits[i])
const newDigit = (digit + offset) % 10 // 超过9则只保留个位数
answer += newDigit.toString()
}
return {
challenge: challengeDigits,
answer: answer,
offset: offset
}
}
/**
* 验证答案(允许±1分钟的时间偏差)
*/
function verifyAnswer(userAnswer, offset) {
// 检查当前时间、前1分钟、后1分钟的三种可能答案
for (let timeOffset = -1; timeOffset <= 1; timeOffset++) {
const challengeDigits = getUTC8TimeDigits(timeOffset)
let correctAnswer = ''
for (let i = 0; i < challengeDigits.length; i++) {
const digit = parseInt(challengeDigits[i])
const newDigit = (digit + offset) % 10
correctAnswer += newDigit.toString()
}
if (userAnswer === correctAnswer) {
return true
}
}
return false
}
/**
* 用户消息转发到管理员 (u2a)
*/
async function forwardMessageU2A(message) {
const user = message.from
const user_id = user.id
const chat_id = message.chat.id
try {
// 1. 管理员跳过所有检查
if (user_id.toString() === ADMIN_UID) {
// 管理员直接跳过验证、屏蔽、频率限制等检查
// 继续处理消息转发
} else {
// 2. 检查验证状态(仅当启用验证功能时)- 使用 Cache API
if (ENABLE_VERIFICATION) {
const verificationState = await verificationCache.getVerification(user_id, 'verification')
const isVerified = await verificationCache.getVerification(user_id, 'verified')
// 如果用户尚未验证
if (!isVerified) {
// 如果还没有发送验证挑战,发送挑战
if (!verificationState) {
const challenge = generateVerificationChallenge(user_id)
await verificationCache.setVerification(user_id, 'verification', {
challenge: challenge.challenge,
answer: challenge.answer,
offset: challenge.offset,
totalAttempts: 0,
timestamp: Date.now()
}, 120) // 120秒后自动过期
await sendMessage({
chat_id: chat_id,
text: `🔐 请输入验证码\n\n将当前UTC+8时间的 时分(HHMM格式,仅数字)四位数字的每一位数字加上 ${challenge.offset},超过9则取个位数\n\n⏰ 请在1分钟内回复验证码,否则将失效\n\n🔐 Please enter the verification code\n\nAdd ${challenge.offset} to each digit of current UTC+8 time in HHMM format (4 digits), if over 9, keep only the ones digit\n\n⏰ Please reply within 1 minute, or the code will expire`,
parse_mode: 'HTML'
})
return
}
// 检查验证码是否过期(1分钟 = 60000毫秒)
const currentTime = Date.now()
const verificationTime = verificationState.timestamp || 0
const timeElapsed = currentTime - verificationTime
if (timeElapsed > 60000) {
// 验证码已过期,删除验证码数据
await verificationCache.deleteVerification(user_id, 'verification')
await sendMessage({
chat_id: chat_id,
text: `⏰ 验证码已失效\n\n您未在1分钟内回复验证码,验证码已失效。\n\n请重新发送消息以获取新的验证码。\n\n⏰ Verification code expired\n\nYou did not reply within 1 minute, the code has expired.\n\nPlease send a new message to get a new verification code.`
})
return
}
// 检查是否已达到最大尝试次数
const totalAttempts = verificationState.totalAttempts || 0
if (totalAttempts >= VERIFICATION_MAX_ATTEMPTS) {
// 永久屏蔽用户
await db.blockUser(user_id, true)
// 标记为验证码超出限制而被屏蔽
await db.setUserState(user_id, 'verification_blocked', true)
await sendMessage({
chat_id: chat_id,
text: `❌ 验证失败次数过多(${VERIFICATION_MAX_ATTEMPTS}次),已被永久屏蔽。\n❌ Too many failed attempts (${VERIFICATION_MAX_ATTEMPTS} times), permanently blocked.`
})
return
}
// 用户已收到挑战,检查答案
const userAnswer = message.text?.trim()
if (!userAnswer) {
await sendMessage({
chat_id: chat_id,
text: `请输入数字答案。\nPlease enter the numeric answer.`
})
return
}
// 验证答案(允许±1分钟偏差)
if (verifyAnswer(userAnswer, verificationState.offset)) {
// 验证成功
await verificationCache.setVerification(user_id, 'verified', true)
await verificationCache.deleteVerification(user_id, 'verification')
await sendMessage({
chat_id: chat_id,
text: `✅ 验证成功!现在您可以发送消息了。\n✅ Verification successful! You can now send messages.`
})
return
} else {
// 验证失败,增加尝试次数
const newTotalAttempts = totalAttempts + 1
// 检查是否达到上限
if (newTotalAttempts >= VERIFICATION_MAX_ATTEMPTS) {
// 永久屏蔽用户
await db.blockUser(user_id, true)
// 标记为验证码超出限制而被屏蔽
await db.setUserState(user_id, 'verification_blocked', true)
await sendMessage({
chat_id: chat_id,
text: `❌ 验证失败次数已达上限(${VERIFICATION_MAX_ATTEMPTS}次),已被永久屏蔽。\n❌ Maximum verification attempts reached (${VERIFICATION_MAX_ATTEMPTS} times), permanently blocked.`
})
return
}
// 重新生成新的验证码
const challenge = generateVerificationChallenge(user_id)
await verificationCache.setVerification(user_id, 'verification', {
challenge: challenge.challenge,
answer: challenge.answer,
offset: challenge.offset,
totalAttempts: newTotalAttempts,
timestamp: Date.now()
}, 120) // 120秒后自动过期
await sendMessage({
chat_id: chat_id,
text: `❌ 验证失败(${newTotalAttempts}/${VERIFICATION_MAX_ATTEMPTS})\n\n🔐 请重新输入验证码\n\n将当前UTC+8时间的 时分(HHMM格式,仅数字)四位数字的每一位数字加上 ${challenge.offset},超过9则取个位数\n\n⏰ 请在1分钟内回复验证码,否则将失效\n\n❌ Verification failed (${newTotalAttempts}/${VERIFICATION_MAX_ATTEMPTS})\n\n🔐 Please re-enter the verification code\n\nAdd ${challenge.offset} to each digit of current UTC+8 time in HHMM format (4 digits), if over 9, keep only the ones digit\n\n⏰ Please reply within 1 minute, or the code will expire`,
parse_mode: 'HTML'
})
return
}
}
}
// 3. 消息频率限制
if (MESSAGE_INTERVAL > 0) {
const lastMessageTime = await db.getLastMessageTime(user_id)
const currentTime = Date.now()
if (currentTime < lastMessageTime + MESSAGE_INTERVAL * 1000) {
const timeLeft = Math.ceil((lastMessageTime + MESSAGE_INTERVAL * 1000 - currentTime) / 1000)
if (timeLeft > 0) {
await sendMessage({
chat_id: chat_id,
text: `发送消息过于频繁,请等待 ${timeLeft} 秒后再试。\nSending messages too frequently, please wait ${timeLeft} seconds before trying again.`
})
return
}
}
await db.setLastMessageTime(user_id, currentTime)
}
// 4. 检查是否被屏蔽
const isBlocked = await db.isUserBlocked(user_id)
if (isBlocked) {
await sendMessage({
chat_id: chat_id,
text: '你已被屏蔽,无法发送消息。\nYou have been blocked and cannot send messages.'
})
return
}
}
// 5. 更新用户信息
await updateUserDb(user)
// 6. 获取或创建话题
let user_data = await db.getUser(user_id)
if (!user_data) {
// 如果用户数据不存在(可能是延迟),等待并重试一次
console.log(`User data not found for ${user_id}, retrying...`)
await delay(100) // 等待100ms
user_data = await db.getUser(user_id)
if (!user_data) {
// 如果仍然不存在,创建默认数据并保存
console.log(`Creating fallback user data for ${user_id}`)
user_data = {
user_id: user_id,
first_name: user.first_name || '未知',
last_name: user.last_name,
username: user.username,
message_thread_id: null,
created_at: Date.now(),
updated_at: Date.now()
}
await db.setUser(user_id, user_data)
}
}
let message_thread_id = user_data.message_thread_id
console.log(`User ${user_id} data loaded, message_thread_id: ${message_thread_id}`)
// 检查话题状态
if (message_thread_id) {
const topicStatus = await db.getTopicStatus(message_thread_id)
console.log(`Topic ${message_thread_id} status check:`, topicStatus)
if (topicStatus.status === 'closed') {
await sendMessage({
chat_id: chat_id,
text: '对话已被对方关闭。您的消息暂时无法送达。如需继续,请等待或请求对方重新打开对话。\nThe conversation has been closed by him. Your message cannot be delivered temporarily. If you need to continue, please wait or ask him to reopen the conversation.'
})
return
} else if (topicStatus.status === 'deleted' || topicStatus.status === 'removed') {
// 话题已被删除,允许重新创建
const oldThreadId = message_thread_id
message_thread_id = null
user_data.message_thread_id = null
await db.setUser(user_id, user_data)
// 清理旧的话题状态记录
await db.setTopicStatus(oldThreadId, 'removed')
console.log(`Topic ${oldThreadId} was deleted/removed, will create new one for user ${user_id}`)
}
}
console.log(`After topic status check, message_thread_id: ${message_thread_id}`)
// 创建新话题
if (!message_thread_id) {
console.log(`Creating new topic for user ${user_id} (${user.first_name || '用户'})`)
try {
const topicName = `${user.first_name || '用户'}|${user_id}`.substring(0, 128)
console.log(`Topic name: ${topicName}`)
const forumTopic = await createForumTopic(ADMIN_GROUP_ID, topicName)
if (forumTopic.ok) {
message_thread_id = forumTopic.result.message_thread_id
user_data.message_thread_id = message_thread_id
await db.setUser(user_id, user_data)
await db.setTopicStatus(message_thread_id, 'opened')
console.log(`✅ Created new topic ${message_thread_id} for user ${user_id}`)
// 发送联系人卡片
console.log(`📱 Sending contact card for user ${user_id} to topic ${message_thread_id}`)
console.log(`User object:`, {
id: user.id,
first_name: user.first_name,
last_name: user.last_name,
username: user.username
})
try {
const contactResult = await sendContactCard(ADMIN_GROUP_ID, message_thread_id, user)
if (contactResult && contactResult.ok) {
console.log(`✅ Contact card sent successfully for user ${user_id}, message_id: ${contactResult.result.message_id}`)
} else {
console.log(`❌ Contact card failed to send for user ${user_id}:`, contactResult)
}
} catch (contactError) {
console.error(`❌ Error sending contact card for user ${user_id}:`, contactError)
}
} else {
await sendMessage({
chat_id: chat_id,
text: '创建会话失败,请稍后再试或联系对方。\nFailed to create session, please try again later or contact him.'
})
return
}
} catch (error) {
console.error('Failed to create topic:', error)
await sendMessage({
chat_id: chat_id,
text: '创建会话时发生错误,请稍后再试。\nAn error occurred while creating the session, please try again later.'
})
return
}
}
console.log(`Final message_thread_id before forwarding: ${message_thread_id}`)
// 7. 处理消息转发
console.log(`Starting message forwarding to topic ${message_thread_id}`)
try {
const params = { message_thread_id: message_thread_id }
// 处理回复消息
if (message.reply_to_message) {
console.log(`User replying to message: ${message.reply_to_message.message_id}`)
const originalId = await db.getMessageMap(`u2a:${message.reply_to_message.message_id}`)
console.log(`Found original group message: ${originalId}`)
if (originalId) {
params.reply_to_message_id = originalId
console.log(`Setting reply_to_message_id: ${originalId}`)
}
}
// 直接转发消息(无论是否为媒体组)
console.log(`Processing message: ${message.message_id}`)
console.log(`Copying message with params:`, {
chat_id: ADMIN_GROUP_ID,
from_chat_id: chat_id,
message_id: message.message_id,
...params
})
let sent
try {
sent = await copyMessage({
chat_id: ADMIN_GROUP_ID,
from_chat_id: chat_id,
message_id: message.message_id,
...params
})
console.log(`Copy message result:`, sent)
} catch (copyError) {
console.error(`❌ copyMessage failed:`, copyError)
console.error(`❌ copyMessage error details:`, {
description: copyError.description,
message: copyError.message,
error_code: copyError.error_code,
ok: copyError.ok
})
throw copyError // 重新抛出错误以便外层catch处理
}
if (sent && sent.ok) {
await db.setMessageMap(`u2a:${message.message_id}`, sent.result.message_id)
await db.setMessageMap(`a2u:${sent.result.message_id}`, message.message_id)
// 存储 admin群组消息ID -> 用户ID 的映射(用于 reaction 同步时定位用户)
await db.setMessageMap(`msg2user:${sent.result.message_id}`, user_id)
// 存储 用户消息ID -> 用户ID 的映射(用于 reaction 反向同步)
await db.setMessageMap(`msg2user:u:${message.message_id}`, user_id)
console.log(`✅ Forwarded u2a: user(${user_id}) msg(${message.message_id}) -> group msg(${sent.result.message_id})`)
console.log(`✅ Stored mapping: u2a:${message.message_id} -> ${sent.result.message_id}`)
console.log(`✅ Stored mapping: a2u:${sent.result.message_id} -> ${message.message_id}`)
console.log(`✅ Stored mapping: msg2user:${sent.result.message_id} -> ${user_id}`)
// 发送"已送达"提示(每日一次),3秒后撤回
await maybeSendDeliveredNotice(user_id, chat_id, { reply_to_message_id: message.message_id })
} else {
console.error(`❌ copyMessage failed, sent.ok = false`)
console.error(`❌ copyMessage response:`, sent)
// 检查是否是话题删除错误
const errorText = (sent.description || '').toLowerCase()
console.log(`🔍 Checking copyMessage error text: "${errorText}"`)
if (errorText.includes('message thread not found') ||
errorText.includes('topic deleted') ||
errorText.includes('thread not found') ||
errorText.includes('topic not found')) {
// 创建一个错误对象来触发删除处理
const deleteError = new Error('Topic deleted')
deleteError.description = sent.description || 'Topic deleted'
throw deleteError
}
}
} catch (error) {
console.error('❌ Error forwarding message u2a:', error)
console.error('❌ Error details:', {
description: error.description,
message: error.message,
error_code: error.error_code,
ok: error.ok,
stack: error.stack
})
// 检查是否是话题删除错误(大小写不敏感)
const errorText = (error.description || error.message || '').toLowerCase()
console.log(`🔍 Checking error text for topic deletion: "${errorText}"`)
console.log(`🔍 Full error object:`, error)
const isTopicDeletedError = errorText.includes('message thread not found') ||
errorText.includes('topic deleted') ||
errorText.includes('thread not found') ||
errorText.includes('topic not found') ||
(errorText.includes('chat not found') && errorText.includes(ADMIN_GROUP_ID))
console.log(`🔍 Is topic deleted error: ${isTopicDeletedError}`)
if (isTopicDeletedError) {
// 话题被删除,清理数据