import type { Context } from "#root/bot/context.js"; import type { Config } from "#root/config.js"; import type { Logger } from "#root/logger.js"; import type { BotConfig } from "grammy"; import { unhandledFeature } from "#root/bot/features/unhandled.js"; import { welcomeFeature } from "#root/bot/features/welcome.js"; import { errorHandler } from "#root/bot/handlers/error.js"; import { i18n } from "#root/bot/i18n.js"; import { session } from "#root/bot/middlewares/session.js"; import { updateLogger } from "#root/bot/middlewares/update-logger.js"; import { autoChatAction } from "@grammyjs/auto-chat-action"; import { hydrate } from "@grammyjs/hydrate"; import { hydrateReply, parseMode } from "@grammyjs/parse-mode"; import { sequentialize } from "@grammyjs/runner"; import { MemorySessionStorage, Bot as TelegramBot } from "grammy"; import { twitterBanlist } from "./features/twitterBanlist.js"; import { metaBanlist } from "./features/metaBanlist.js"; import { tiktokBanlist } from "./features/tiktokBanlist.js"; import { botInfoCommand } from "./features/botInfoCommand.js"; import { helpCommand } from "./features/helpCommand.js"; import { embedCheck } from "./features/embedCheck.js"; import { registerGroup } from "./features/registerGroupCommand.js"; import { getGroupStats } from "./features/getGroupStatsCommand.js"; import { statsSiteCommand } from "./features/botStatsSiteCommand.js"; interface Dependencies { config: Config; logger: Logger; } function getSessionKey(ctx: Omit) { return ctx.chat?.id.toString(); } export function createBot( token: string, dependencies: Dependencies, botConfig?: BotConfig ) { const { config, logger } = dependencies; const bot = new TelegramBot(token, botConfig); bot.use(async (ctx, next) => { ctx.config = config; ctx.logger = logger.child({ update_id: ctx.update.update_id }); await next(); }); const protectedBot = bot.errorBoundary(errorHandler); // Middlewares bot.api.config.use(parseMode("HTML")); if (config.isPollingMode) protectedBot.use(sequentialize(getSessionKey)); if (config.isDebug) protectedBot.use(updateLogger()); protectedBot.use(autoChatAction(bot.api)); protectedBot.use(hydrateReply); protectedBot.use(hydrate()); protectedBot.use( session({ getSessionKey, storage: new MemorySessionStorage() }) ); protectedBot.use(i18n); // Handlers protectedBot.use(welcomeFeature); // Commands protectedBot.use(botInfoCommand); protectedBot.use(helpCommand); protectedBot.use(registerGroup); protectedBot.use(getGroupStats); protectedBot.use(statsSiteCommand); // banlist Feature protectedBot.use(twitterBanlist); protectedBot.use(metaBanlist); protectedBot.use(tiktokBanlist); protectedBot.use(embedCheck); // must be the last handler protectedBot.use(unhandledFeature); return bot; } export type Bot = ReturnType;