Files
hereconnect/services/tg-bot/src/bot/index.ts
T

60 lines
2.0 KiB
TypeScript
Raw Normal View History

2024-12-10 13:21:38 +02:00
import { Bot, session } from "grammy";
import { conversations, createConversation } from "@grammyjs/conversations";
2024-12-12 17:45:01 +02:00
import { MyContext } from "../types/myContext";
import { env } from "../config/env";
2024-12-12 13:30:28 +02:00
import { CouchDBStorageAdapter } from "./storageAdapters/CouchDBStorageAdapter";
2024-12-10 13:21:38 +02:00
import { loadUserMiddleware } from "./middleware/loadUser";
2024-12-12 17:45:01 +02:00
import { tgBotSessionsDb } from "../dbs";
2024-12-10 13:21:38 +02:00
import { startCommand } from "./commands/start";
import { helpCommand } from "./commands/help";
import { newCommand } from "./commands/new";
import { manageCommand } from "./commands/manage";
import { callbackQueryHandler } from "./callbackHandlers";
import { newQRCodeConversation } from "./conversations/newQRCodeConversation";
import { hydrateReply } from "@grammyjs/parse-mode";
export { setupCommands } from "./commands/setupCommands";
export const createBot = ({
abortController,
}: {
abortController: AbortController;
}) => {
const storage = new CouchDBStorageAdapter(tgBotSessionsDb, {
softDelete: true,
type: "tg_bot_session",
});
// Инициализируем бота с нужным типом контекста
const bot = new Bot<MyContext>(env.TELEGRAM_BOT_TOKEN, {
client: {
baseFetchConfig: {
signal: abortController.signal,
},
2024-12-12 17:45:01 +02:00
},
});
2024-12-10 13:21:38 +02:00
bot.use(hydrateReply);
2024-12-10 13:21:38 +02:00
// Подключаем сессии. По необходимости определите initial state для сессии
bot.use(session({ storage, initial: () => ({}) }));
2024-12-10 13:21:38 +02:00
// Подключаем conversations для многошаговых сценариев
bot.use(conversations());
bot.use(createConversation(newQRCodeConversation));
2024-12-10 13:21:38 +02:00
// Middleware для загрузки или создания пользователя
bot.use(loadUserMiddleware);
2024-12-12 17:45:01 +02:00
// Регистрация команд
bot.command("start", startCommand);
bot.command("help", helpCommand);
bot.command("new", newCommand);
bot.command("manage", manageCommand);
2024-12-12 17:45:01 +02:00
// Обработка callback_query
bot.on("callback_query:data", callbackQueryHandler);
2024-12-10 13:21:38 +02:00
return bot;
};