forked from manzoorwanijk/telegram-bot-api-worker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
81 lines (67 loc) · 1.82 KB
/
index.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
/*
* The regex to get the bot_token and api_method from request URL
* as the first and second backreference respectively.
*/
const URL_PATH_REGEX = /^\/bot(?<bot_token>[^/]+)\/(?<api_method>[a-z]+)/i;
/**
* Sends a POST request with JSON data to Telegram Bot API
* and reads in the response body.
* @param {Request} request the incoming request
*/
async function handleTelegramRequest(request) {
const url = new URL(request.url);
// point the URL to Telegram Bot API
url.hostname = 'api.telegram.org';
// create a new request with the modified URL
const newRequest = new Request(url.toString(), request);
// Get the response from API.
const response = await fetch(newRequest);
return response;
}
/**
* Handles the request to the root
*/
function handleRootRequest() {
const result = 'Everything looks good! You are ready to use your CloudFlare worker.';
return new Response(JSON.stringify({ ok: true, result }), {
status: 200,
statusText: result,
headers: {
'content-type': 'application/json',
},
});
}
/**
* Handles the 404 request
*/
async function handle404Request() {
const description = 'No matching route found';
const error_code = 404;
return new Response(JSON.stringify({ ok: false, error_code, description }), {
status: error_code,
statusText: description,
headers: {
'content-type': 'application/json',
},
});
}
/**
* Handles the incoming request.
* @param {Request} request the incoming request.
*/
async function handleRequest(request) {
const { pathname } = new URL(request.url);
if (URL_PATH_REGEX.test(pathname)) {
return await handleTelegramRequest(request);
}
if (pathname === '/') {
return handleRootRequest();
}
return handle404Request();
}
/**
* Hook into the fetch event.
*/
addEventListener('fetch', (event) => {
event.respondWith(handleRequest(event.request));
});