-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathworker.js
145 lines (129 loc) · 4.66 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
/////////////////////////////////////////////////////////////////////////////////
// serverless telegram bot connected to database channel
// Creator: Arashnm80
// https://github.com/arashnm80/worker-telegram-bot-with-database-channel
/////////////////////////////////////////////////////////////////////////////////
const TOKEN = "" // Get it from @BotFather https://core.telegram.org/bots#6-botfather
const databaseChannel = "" // database channel that holds responses
const commands = { // numbers are message IDs in the database channel
"/example": 5, // can be a command
"another example": 6, // can be a normal text
"حالت چطوره": 10, // can be in any language
"multiple examples": [15, 16, 17, 18] // can be a list of messages
}
/////////////////////////////////////////////////////////////////////////////////
// other vars
const WEBHOOK = '/endpoint' // don't change it unless you're a programmer and you know what you're doing
const SECRET = TOKEN.replace(/[^a-zA-Z0-9]/g, ''); // get SECRET from TOKEN, we could've set it manually to a random value with (A-Z, a-z, 0-9, _ and -) too
const promoteMessage = 0 // set it to a non-zero id of a message to be sent as ad after every command (leave it to 0 if you don't need)
/**
* 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) {
var command = message.text
var returnMessage;
if(command in commands){
if(Array.isArray(commands[command])){ // it is a list of messages
for (let c of commands[command]) {
returnMessage = await copyMessage(message.chat.id, databaseChannel, c)
}
} else { // it is a single message
returnMessage = await copyMessage(message.chat.id, databaseChannel, commands[command])
}
if(promoteMessage !== 0){ // send promoteMessage if it exists (is non-zero)
await copyMessage(message.chat.id, databaseChannel, promoteMessage)
}
return returnMessage;
} else {
return sendPlainText(message.chat.id, 'command not defined.')
}
}
/**
* Send plain text message
* https://core.telegram.org/bots/api#sendmessage
*/
async function sendPlainText (chatId, text) {
return (await fetch(apiUrl('sendMessage', {
chat_id: chatId,
text
}))).json()
}
/**
* 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))
}
/**
* 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}`
}
/**
* Copy message from database channel
* https://core.telegram.org/bots/api#copymessage
*/
async function copyMessage (chatId, fromChatId, messageId) {
return (await fetch(apiUrl('copyMessage', {
chat_id: chatId,
from_chat_id: fromChatId,
message_id: messageId
}))).json()
}