-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.ts
65 lines (53 loc) · 1.98 KB
/
index.ts
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
import "dotenv/config";
import { BOT_TOKEN, HOST, PORT, WEBHOOK_URL, bots } from "./constants";
import { NextFunction, Request, Response } from "express";
import botCreator from "./bot";
import express from "express";
import { run } from "@grammyjs/runner";
import { webhookCallback } from "grammy";
const app = express();
app.use(express.json());
app.use((req: Request, res: Response, next: NextFunction) => {
console.log(`${new Date().toLocaleString()} ${req.method} ${req.path}`);
next();
});
app.post("/bot:token", async (req: Request, res: Response) => {
const bot_token = req.params.token;
let bot = bots.get(bot_token);
if (!bot) {
bot = botCreator(bot_token);
bots.set(bot_token, bot);
}
try {
await webhookCallback(bot, "express")(req, res);
} catch (error: any) {
console.error(error?.description ?? error?.message ?? error);
res.status(200).end();
}
});
app.get("/ping", (req: Request, res: Response) => {
res.end("pong");
});
app.all("*", async (req: Request, res: Response) => {
const resp = await fetch("https://example.com");
res.setHeader("Content-Type", "text/html").end(await resp.text());
});
app.listen(PORT, HOST, () => {
console.log(`Server listening on http://${HOST}:${PORT}`);
if (!WEBHOOK_URL && !BOT_TOKEN) {
console.warn("WEBHOOK_URL or BOT_TOKEN not set in .env file, new bot cannot be created");
}
if (!WEBHOOK_URL && BOT_TOKEN) {
console.info("Webhook URL not set, starting bot using polling");
const bot = botCreator(BOT_TOKEN);
run(bot);
} else if (WEBHOOK_URL && !BOT_TOKEN) {
console.warn("Bot token not set, starting webhook server only");
} else if (WEBHOOK_URL && BOT_TOKEN) {
console.info("Starting bot using webhook");
const bot = botCreator(BOT_TOKEN);
bot.api.setWebhook((WEBHOOK_URL + "/bot" + BOT_TOKEN) as string);
bots.set(BOT_TOKEN, bot);
}
console.log("Server started");
});