// utils/handlerUtils.ts import { BotContext } from "../types/botTypes"; import { createLogger } from '../../utils/logger'; import { AuthService } from '../services/auth'; import { messageManager } from './messageManager'; import { getMainMenuKeyboard } from './keyboardUtils'; const logger = createLogger('HandlerUtils'); const authService = AuthService.getInstance(); /** * Creates a standardized message reply handler with error handling * @param replyFunction Function that returns the message and options to send * @returns A function that handles the reply with proper error handling */ export const messageReplyHandler = ( replyFunction: (ctx: BotContext) => Promise<{message: string, options?: any}> | {message: string, options?: any} ) => async (ctx: BotContext) => { try { // Execute the reply function to get message content and options const result = await Promise.resolve(replyFunction(ctx)); // Get the message ID to reply to const replyToMessageId = ctx.message?.message_id; // Define default options including parse_mode const defaultOptions = { parse_mode: 'HTML' }; // Add reply_to_message_id to options if not already set const finalOptions = { ...defaultOptions, ...result.options, reply_to_message_id: replyToMessageId }; // Send the reply with the message and options return await ctx.reply(result.message, finalOptions); } catch (error: any) { // Log the error logger.error(`Error in message reply handler: ${error.message}`); // Send a generic error message to the user return ctx.reply("⚠️ حدث خطأ أثناء معالجة طلبك. الرجاء المحاولة مرة أخرى."); } }; /** * Creates a standardized callback query handler with error handling * @param replyFunction Function that returns the message and options to send after answering callback * @returns A function that handles the callback with proper error handling */ export const callbackReplyHandler = ( replyFunction: (ctx: BotContext) => Promise<{message: string, options?: any}> | {message: string, options?: any} ) => async (ctx: BotContext) => { try { // Answer the callback query first await ctx.answerCbQuery(); // Execute the reply function to get message content and options const result = await Promise.resolve(replyFunction(ctx)); // Send the reply with the message and any provided options return await ctx.reply(result.message, result.options); } catch (error: any) { // Log the error logger.error(`Error in callback reply handler: ${error.message}`); // Send a generic error message to the user return ctx.reply("⚠️ حدث خطأ أثناء معالجة طلبك. الرجاء المحاولة مرة أخرى."); } }; export const authCheckHandler = ( handler: (ctx: BotContext, ...args: T) => Promise<{message: string, options?: any}> | {message: string, options?: any} ) => async (ctx: BotContext, ...args: T) => { const telegramId = ctx.from?.id; if (!telegramId || !authService.isUserLoggedIn(telegramId, ctx)) { return { message: messageManager.getMessage('auth_required'), options: getMainMenuKeyboard() }; } return handler(ctx, ...args); };