ussd-tg-proxy/src/index.js

52 lines
1.3 KiB
JavaScript

const express = require("express");
const { webhookCallback } = require("grammy");
const config = require("./config");
const cache = require("./cache");
const bot = require("./bot");
const log = require("./log");
if (process.env.NODE_ENV !== "production") {
bot.api.deleteWebhook().then(() => {
log.info("starting bot in polling mode");
bot.start();
});
bot.catch((err) => {
log.error(err);
});
} else {
const app = express();
app.use(express.json());
log.info("starting bot in webhook mode");
app.use(webhookCallback(bot, "express"));
app.use(function (err, _, res, _) {
log.error(err);
return res.status(500);
});
const webhookEndpoint = `${config.get("SERVER_ENDPOINT")}/${config.get(
"TELEGRAM_TOKEN"
)}`;
log.debug(`setting webhook at ${webhookEndpoint}`);
bot.api.setWebhook(webhookEndpoint).then(async () => {
const webhookInfo = await bot.api.getWebhookInfo();
log.info(webhookInfo, "webhook successfully set");
});
log.info("starting server");
const server = app.listen(
config.get("SERVER_PORT"),
config.get("SERVER_HOST")
);
for (const signal of ["SIGINT", "SIGTERM"]) {
process.once(signal, async () => {
log.info("shutting down server");
await server.close();
await cache.disconnect();
process.exit(0);
});
}
}