-
Notifications
You must be signed in to change notification settings - Fork 1
/
worker.js
268 lines (238 loc) · 8.46 KB
/
worker.js
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
/**
* Welcome to Cloudflare Workers! This is your first worker.
*
* - Run "npm run dev" in your terminal to start a development server
* - Open a browser tab at http://localhost:8787/ to see your worker in action
* - Run "npm run deploy" to publish your worker
*
* Learn more at https://developers.cloudflare.com/workers/
*/
const TOKEN = ENV_BOT_TOKEN // Get it from @BotFather
const WEBHOOK = '/endpoint'
const SECRET = ENV_BOT_SECRET // A-Z, a-z, 0-9, _ and -
const ADMIN_UID = ENV_ADMIN_UID // your user id, get it from https://t.me/username_to_id_bot
const NOTIFY_INTERVAL = 3600 * 1000;
const fraudDb = 'https://raw.githubusercontent.com/LloydAsp/nfd/main/data/fraud.db';
const notificationUrl = 'https://raw.githubusercontent.com/LloydAsp/nfd/main/data/notification.txt'
const startMsgUrl = 'https://raw.githubusercontent.com/Sevtinge/Telegram_PM_Bot/main/startMessage.md';
const enable_notification = false
/**
* Return url to telegram api, optionally with parameters added
*/
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 forwardMessage(msg){
return requestTelegram('forwardMessage', makeReqBody(msg))
}
/**
* Wait for requests to the worker
*/
addEventListener('fetch', event => {
const url = new URL(event.request.url)
if (url.pathname === WEBHOOK) {
event.respondWith(handleWebhook(event))
} else if (url.pathname === '/registerWebhook') {
event.respondWith(registerWebhook(event, url, WEBHOOK, SECRET))
} else if (url.pathname === '/unRegisterWebhook') {
event.respondWith(unRegisterWebhook(event))
} else {
event.respondWith(new Response('No handler for this request'))
}
})
/**
* Handle requests to WEBHOOK
* https://core.telegram.org/bots/api#update
*/
async function handleWebhook (event) {
// Check secret
if (event.request.headers.get('X-Telegram-Bot-Api-Secret-Token') !== SECRET) {
return new Response('Unauthorized', { status: 403 })
}
// Read request body synchronously
const update = await event.request.json()
// Deal with response asynchronously
event.waitUntil(onUpdate(update))
return new Response('Ok')
}
/**
* Handle incoming Update
* https://core.telegram.org/bots/api#update
*/
async function onUpdate (update) {
if ('message' in update) {
await onMessage(update.message)
}
}
/**
* Handle incoming Message
* https://core.telegram.org/bots/api#message
*/
async function onMessage (message) {
if(message.text === '/start'){
let startMsg = await fetch(startMsgUrl).then(r => r.text())
return sendMessage({
chat_id:message.chat.id,
text:startMsg,
})
}
if(message.chat.id.toString() === ADMIN_UID){
if(!message?.reply_to_message?.chat){
return sendMessage({
chat_id:ADMIN_UID,
text:'**HOW TO USE**\n\nReply to a forwarded message and send a reply message, or command `/block`, `/unblock`, `/checkblock`, etc.\n---\n**使用方法**\n\n回复转发的消息,并发送回复消息,或者`/block`、`/unblock`、`/checkblock`等指令。'
})
}
if(/^\/block$/.exec(message.text)){
return handleBlock(message)
}
if(/^\/unblock$/.exec(message.text)){
return handleUnBlock(message)
}
if(/^\/checkblock$/.exec(message.text)){
return checkBlock(message)
}
let guestChantId = await nfd.get('msg-map-' + message?.reply_to_message.message_id,
{ type: "json" })
return copyMessage({
chat_id: guestChantId,
from_chat_id:message.chat.id,
message_id:message.message_id,
})
}
return handleGuestMessage(message)
}
async function handleGuestMessage(message){
let chatId = message.chat.id;
let isblocked = await nfd.get('isblocked-' + chatId, { type: "json" })
if(isblocked){
return sendMessage({
chat_id: chatId,
text:'**TIP**\n\nYour are blocked.\n---\n**提示**\n\n您已被封锁。'
})
}
let forwardReq = await forwardMessage({
chat_id:ADMIN_UID,
from_chat_id:message.chat.id,
message_id:message.message_id
})
console.log(JSON.stringify(forwardReq))
if(forwardReq.ok){
await nfd.put('msg-map-' + forwardReq.result.message_id, chatId)
}
return handleNotify(message)
}
async function handleNotify(message){
// 先判断是否是诈骗人员,如果是,则直接提醒
// 如果不是,则根据时间间隔提醒:用户id,交易注意点等
let chatId = message.chat.id;
if(await isFraud(chatId)){
return sendMessage({
chat_id: ADMIN_UID,
text:`**TIP **\n\nThis user is fraudulent. (UID${chatId})\n---\n**提示**\n\n该用户存在欺诈行为。(UID${chatId})`
})
}
if(enable_notification){
let lastMsgTime = await nfd.get('lastmsg-' + chatId, { type: "json" })
if(!lastMsgTime || Date.now() - lastMsgTime > NOTIFY_INTERVAL){
await nfd.put('lastmsg-' + chatId, Date.now())
return sendMessage({
chat_id: ADMIN_UID,
text:await fetch(notificationUrl).then(r => r.text())
})
}
}
}
async function handleBlock(message){
let guestChantId = await nfd.get('msg-map-' + message.reply_to_message.message_id,
{ type: "json" })
if(guestChantId === ADMIN_UID){
return sendMessage({
chat_id: ADMIN_UID,
text:'**TIP**\n\nCannot block yourself.\n---\n**提示**\n\n不能封锁自己。'
})
}
await nfd.put('isblocked-' + guestChantId, true)
return sendMessage({
chat_id: ADMIN_UID,
text: `**TIP**\n\nUser blocked. (UID:${guestChantId})\n---\n**提示**\n\n用户封锁成功。(UID:${guestChantId})`,
})
}
async function handleUnBlock(message){
let guestChantId = await nfd.get('msg-map-' + message.reply_to_message.message_id,
{ type: "json" })
await nfd.put('isblocked-' + guestChantId, false)
return sendMessage({
chat_id: ADMIN_UID,
text:`**TIP**\n\nUser unblocked. (UID:${guestChantId})\n---\n**提示**\n\n用户解除封锁成功。(UID:${guestChantId})`,
})
}
async function checkBlock(message){
let guestChantId = await nfd.get('msg-map-' + message.reply_to_message.message_id,
{ type: "json" })
let blocked = await nfd.get('isblocked-' + guestChantId, { type: "json" })
return sendMessage({
chat_id: ADMIN_UID,
text: (blocked ? `**TIP**\n\nThe user has been blocked. (UID:${guestChantId})\n---\n**提示**\n\n该用户已被封锁。(UID:${guestChantId})` : `**TIP**\n\nThe user is not blocked. (UID:${guestChantId})\n---\n**提示**\n\n该用户未被封锁。(UID:${guestChantId})`)
})
}
/**
* Send plain text message
* https://core.telegram.org/bots/api#sendmessage
*/
async function sendPlainText (chatId, text) {
return sendMessage({
chat_id: chatId,
text
})
}
/**
* Set webhook to this worker's url
* https://core.telegram.org/bots/api#setwebhook
*/
async function registerWebhook (event, requestUrl, suffix, secret) {
// https://core.telegram.org/bots/api#setwebhook
const webhookUrl = `${requestUrl.protocol}//${requestUrl.hostname}${suffix}`
const r = await (await fetch(apiUrl('setWebhook', { url: webhookUrl, secret_token: secret }))).json()
return new Response('ok' in r && r.ok ? 'Ok' : JSON.stringify(r, null, 2))
}
/**
* Remove webhook
* https://core.telegram.org/bots/api#setwebhook
*/
async function unRegisterWebhook (event) {
const r = await (await fetch(apiUrl('setWebhook', { url: '' }))).json()
return new Response('ok' in r && r.ok ? 'Ok' : JSON.stringify(r, null, 2))
}
async function isFraud(id){
id = id.toString()
let db = await fetch(fraudDb).then(r => r.text())
let arr = db.split('\n').filter(v => v)
console.log(JSON.stringify(arr))
let flag = arr.filter(v => v === id).length !== 0
console.log(flag)
return flag
}