aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJan Tuomi <jan.tuomi@valuemotive.com>2021-04-18 18:07:54 +0300
committerJan Tuomi <jan.tuomi@valuemotive.com>2021-04-18 18:07:54 +0300
commitbaacc7676c688cd2728033e9051208d655255ee5 (patch)
tree5a3819b1c5f6ad616d82f84b3a62cca20d54c0f7 /src
parent12f3de7a9ec911cf5945eee31c7680aa75c4f8af (diff)
Work on tg bot
Diffstat (limited to 'src')
-rw-r--r--src/config.ts51
-rw-r--r--src/index.ts32
-rw-r--r--src/middleware.ts19
3 files changed, 87 insertions, 15 deletions
diff --git a/src/config.ts b/src/config.ts
new file mode 100644
index 0000000..dc3889a
--- /dev/null
+++ b/src/config.ts
@@ -0,0 +1,51 @@
+import dotenv from "dotenv";
+
+if (!process.env.SKIP_DOTENV) {
+ dotenv.config();
+}
+
+class ConfigError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "ConfigError";
+ }
+}
+
+const tgWebhookUrl = process.env.TELEGRAM_WEBHOOK_URL || null;
+if (!tgWebhookUrl) {
+ throw new ConfigError("Missing env var TELEGRAM_WEBHOOK_URL");
+}
+
+const tgBotToken = process.env.TELEGRAM_BOT_TOKEN || null;
+if (!tgBotToken) {
+ throw new ConfigError("Missing env var TELEGRAM_BOT_TOKEN");
+}
+
+const tgUserIds = process.env.TELEGRAM_USER_IDS
+ ? process.env.TELEGRAM_USER_IDS?.split(",")
+ .map(Number.parseInt)
+ : null;
+if (!tgUserIds) {
+ throw new ConfigError("Missing env var TELEGRAM_USER_IDS");
+}
+
+const sheetsSpreadsheetId = process.env.SHEETS_SPREADSHEET_ID || null;
+if (!sheetsSpreadsheetId) {
+ throw new ConfigError("Missing env var SHEETS_SPREADSHEET_ID");
+}
+
+const sheetsRange = process.env.SHEETS_RANGE || null;
+if (!sheetsRange) {
+ throw new ConfigError("Missing env var SHEETS_RANGE");
+}
+
+const config = {
+ port: process.env.PORT ? Number(process.env.PORT) : 3000,
+ tgWebhookUrl,
+ tgBotToken,
+ tgUserIds,
+ sheetsSpreadsheetId,
+ sheetsRange,
+};
+
+export default config;
diff --git a/src/index.ts b/src/index.ts
index 3ff5de7..71e239f 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -1,9 +1,16 @@
import { App } from "@tinyhttp/app";
import { logger } from "@tinyhttp/logger";
-import { auth } from "./middleware";
+import { Telegraf } from "telegraf";
+import config from "./config";
+import { tgMiddleware } from "./middleware";
const app = new App();
-const port = process.env.PORT ? Number(process.env.PORT) : 3000;
+console.log(`Setting up Telegram bot with token ${config.tgBotToken}`);
+const bot = new Telegraf(config.tgBotToken);
+
+bot.use(tgMiddleware.auth);
+bot.command("/start", (ctx) => ctx.reply("started"));
+bot.command("/stop", (ctx) => ctx.reply("stopped"));
app
.use(logger({
@@ -11,19 +18,20 @@ app
format: "YYYY-MM-DDTHH:mm:ssZ[Z]",
},
}))
- .use(auth)
+ .use(bot.webhookCallback("/webhook/telegram"))
.get("/", (_, res) => {
- res.send({ foo: "bar" });
- })
- .post("/webhook/start", (_req, res) => {
- res.send({ webhook: "start" });
- })
- .post("/webhook/stop", (_req, res) => {
- res.send({ webhook: "stop" });
+ res.send({ service: "hommabot2 API" });
})
.post("/scheduler/trigger", (_req, res) => {
res.send({ scheduler: "trigger" });
});
-console.log(`Serving on http://localhost:${port}`);
-app.listen(port);
+console.log(`Setting up webhook on ${config.tgWebhookUrl}`);
+bot.telegram.setWebhook(config.tgWebhookUrl);
+
+console.log(`Serving on http://localhost:${config.port}`);
+app.listen(config.port);
+
+// Enable graceful stop
+process.once("SIGINT", () => bot.stop("SIGINT"));
+process.once("SIGTERM", () => bot.stop("SIGTERM"));
diff --git a/src/middleware.ts b/src/middleware.ts
index bdc006a..e2814e0 100644
--- a/src/middleware.ts
+++ b/src/middleware.ts
@@ -1,5 +1,18 @@
-import { NextFunction, Request, Response } from "@tinyhttp/app";
+import { Context } from "telegraf";
+import config from "./config";
-export const auth = async (_req: Request, _res: Response, next: NextFunction): Promise<void> => {
- await next();
+const auth = async (ctx: Context, next: () => Promise<void>): Promise<void> => {
+ const userId = ctx.message?.from.id;
+
+ if (!userId || !config.tgUserIds.includes(userId)) {
+ ctx.reply("Käyttäjälläsi ei ole oikeuksia startata HommaBottia.");
+ } else {
+ await next();
+ }
+};
+
+export const tgMiddleware = {
+ auth,
};
+
+export const httpMiddleware = {};