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
|
// index.js
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
if (request.method === 'POST') {
let body = await request.text()
let message = JSON.parse(body).message
let chatId = message.chat.id
let text = message.text
let response = await handleCommand(chatId, text)
return new Response(response, {
headers: {
'Content-Type': 'application/json'
}
})
}
return new Response('OK')
}
async function handleCommand(chatId, text) {
let words = text.split(' ')
let command = words[0]
let name = words.slice(1).join(' ')
let responseText
switch(command) {
case '/打卡':
responseText = await countLog(chatId, name, '打卡')
break
case '/重置打卡':
responseText = await resetCount(chatId, name)
break
case '/查询打卡历史':
responseText = await getHistory(chatId, name)
break
default:
responseText = '未识别的命令'
}
return JSON.stringify({
method: 'sendMessage',
chat_id: String(chatId),
text: responseText
})
}
// 连接数据库
const db = D1.table('count_log')
// 打卡
async function countLog(chatId, name, type) {
let date = new Date().toISOString().slice(0, 10)
// 查询今天是否已经打卡
let result = await db.get(name, date)
if (result) {
// 如果今天已经打卡,累加次数
await db.put(name, date, {
count_value: result.count_value + 1
})
} else {
// 如果今天还没打卡,插入新记录
await db.insert({
count_name: name,
count_type: type,
count_value: 1,
count_date: date
})
}
// 查询最新次数
result = await db.get(name, date)
return `${name}打卡成功,累计打卡${result.count_value}次`
}
// 重置打卡次数
async function resetCount(chatId, name) {
let date = new Date().toISOString().slice(0, 10)
await db.insert({
count_name: name,
count_type: '重置',
count_value: 0,
count_date: date
})
return `重置打卡成功,${name}累计打卡0次`
}
// 查询打卡历史
async function getHistory(chatId, name) {
let records = await db.filter(record => record.count_name === name)
.sortBy('count_date')
.reverse()
.limit(30)
let history = records.map(record => {
return `${record.count_name} ${record.count_date}`
}).join('\n')
return history
}
|