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 (config.get("TELEGRAM_POLLING")) { 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); }); } }