-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.ts
More file actions
79 lines (67 loc) · 2.58 KB
/
Copy pathhandler.ts
File metadata and controls
79 lines (67 loc) · 2.58 KB
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
import {APIGatewayProxyHandler, SQSHandler} from 'aws-lambda';
import 'source-map-support/register';
import {ReceptionistBot} from "./src/receptionistBot";
import {Update} from "node-telegram-bot-api";
import {ResizeBot} from "./src/resizeBot";
import * as path from "path";
import { Logger } from './src/logger';
import { withTimeout, TimeoutError } from './src/utils';
const TELEGRAM_BOT_TOKEN = process.env.TELEGRAM_BOT_TOKEN;
const RESIZE_REQUEST_QUEUE_NAME = process.env.RESIZE_REQUEST_QUEUE_NAME;
const RECEIVE_TELEGRAM_TIMEOUT_MS = 5000;
const RESIZE_IMAGE_TIMEOUT_MS = 30000;
export const receiveTelegram: APIGatewayProxyHandler = async (event) => {
const receptionistBot = new ReceptionistBot(TELEGRAM_BOT_TOKEN, RESIZE_REQUEST_QUEUE_NAME);
let update: Update;
try {
update = JSON.parse(event.body);
validateUpdate(update);
} catch (e) {
Logger.error("Couldn't parse request. Non-existent or malformed body", e);
return { statusCode: 400, body: "BAD REQUEST"}
}
try {
const success = await withTimeout(
RECEIVE_TELEGRAM_TIMEOUT_MS,
receptionistBot.receiveUpdate(update)
);
if (success) {
return { statusCode: 200, body: "OK" };
} else {
Logger.error(`ReceptionistBot was unable to process update #${update.update_id}`);
return { statusCode: 200, body: unableToProcessUpdateResponse(update)}
}
} catch (e) {
Logger.error("Unexpected error while processing update", e);
return { statusCode: 200, body: unableToProcessUpdateResponse(update) }
}
};
function validateUpdate(update: Update) {
if(!update || !update.update_id) {
throw new Error("Update missing 'update_id'");
}
}
function unableToProcessUpdateResponse(update: Update): string {
const chatId = update.message && update.message.chat && update.message.chat.id
if(chatId) {
return JSON.stringify({
method: "sendMessage",
chat_id: chatId,
text: "Sorry. I'm unable to process your request at this time. Please try again later."
})
} else {
return "";
}
}
export const processResizeRequest: SQSHandler = async (event) => {
const records = event.Records || [];
await Promise.all(records.map(async record => {
try {
const resizeBot = new ResizeBot(TELEGRAM_BOT_TOKEN, path.join("/", "tmp", record.messageId));
Logger.info(`Received a SQS message #${record.messageId}`, record);
await withTimeout(RESIZE_IMAGE_TIMEOUT_MS, resizeBot.processResizeRequest(JSON.parse(record.body)));
} catch (e) {
Logger.error(`Error while processing the SQS message #${record.messageId}`, e)
}
}));
};