-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
60 lines (55 loc) · 1.9 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
/**
* Escapes special characters in a string to their HTML entities.
*
* @param {string} text - The string to escape.
* @return {string} The escaped string.
*/
function escapeHTML(text) {
return text
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
/**
* Lambda function handler for incoming webhook events from SMS Gateway.
* Validates the API key, processes the message, and forwards it to the specified Telegram chat.
*
* @param {Object} event - The event object passed to the handler.
* @param {Object} context - The context object passed to the handler.
* @returns {Promise} - A promise that resolves to the response object.
*/
module.exports.handler = async (event, context) => {
// Check if the API key is valid
const apiKey = event.queryStringParameters.apiKey;
if (apiKey !== process.env.API_KEY) {
return {
statusCode: 401,
body: 'Unauthorized' // Return 401 Unauthorized if the API key is invalid
};
}
// Parse the request body
const body = JSON.parse(event.body);
const payload = body.payload;
const phoneNumber = payload.phoneNumber;
const message = escapeHTML(payload.message);
// Prepare the message to be sent to Telegram
const text = `New message from <b>${phoneNumber}</b>:\n<code>${message}</code>`;
// Send the message to Telegram
await fetch('https://api.telegram.org/bot' + process.env.TELEGRAM_BOT_TOKEN + '/sendMessage', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
chat_id: process.env.TELEGRAM_CHAT_ID,
text,
parse_mode: 'HTML'
})
});
return {
statusCode: 200,
body: 'OK' // Return 200 OK if the message was sent successfully
};
};