//loadCommands.ts
import { XarV } from "../global";
import { readdirSync } from "fs";
import { join } from "path";
import { handleStart } from "./handler/onStart";
import { handleReply } from "./handler/onReply";

declare global {
  var XarV2: {
    onReply: Map<any, any>;
  };
}

if (!global.XarV2) {
  global.XarV2 = {
    onReply: new Map()
  };
}

export const loadCommands = (bot: any) => {
  const scriptsPath = join(import.meta.dir, "..", "..", "scripts", "cmds");
  const commandFiles = readdirSync(scriptsPath).filter(file => file.endsWith(".js"));

  for (const file of commandFiles) {
    const { XarV2: command } = require(join(scriptsPath, file));
    if (command && command.config && command.onStart) {
      XarV.commands.set(command.config.name, command);
      command.config.aliases.forEach((alias: string) => XarV.aliases.set(alias, command.config.name));
      XarV.commandFilesPath.push({ filePath: join(scriptsPath, file), commandName: [command.config.name, ...command.config.aliases] });
    }
  }

  bot.on("message", async (msg: any) => {
    const messageText = msg.text ? msg.text.trim() : "";
    const prefix = bot.prefix || "/";
    const [cmdText, ...args] = messageText.split(/\s+/);
    let commandName = cmdText;
    let usePrefix = true;

    if (await handleReply(bot, msg)) {
      return;
    }

    if (cmdText.startsWith(prefix)) {
      commandName = cmdText.slice(prefix.length);
    } else {
      usePrefix = false;
    }

    const command = XarV.commands.get(commandName) || XarV.commands.get(XarV.aliases.get(commandName));
    if (!command) {
      if (usePrefix || messageText === prefix) {
        bot.sendMessage(msg.chat.id, `Command "${commandName}" not found.`);
      }
      return;
    }

    if (command.config.usePrefix !== false && !usePrefix) {
      bot.sendMessage(msg.chat.id, `Please use the correct prefix: ${prefix}${commandName}`);
      return;
    }

    await handleStart(bot, msg, commandName, args);
  });

  // Add callback query handler
  bot.on("callback_query", async (callbackQuery: any) => {
    const [commandName] = callbackQuery.data.split(':');
    const command = XarV.commands.get(commandName);

    if (command && command.onCallback) {
      try {
        await command.onCallback({
          api: bot,
          event: callbackQuery,
          message: {
            send: (text: string, options = {}) => bot.sendMessage(callbackQuery.message.chat.id, text, options),
            reply: (text: string, options = {}) => bot.sendMessage(callbackQuery.message.chat.id, text, { ...options, reply_to_message_id: callbackQuery.message.message_id }),
            edit: (text: string, options = {}) => bot.editMessageText(text, { chat_id: callbackQuery.message.chat.id, message_id: callbackQuery.message.message_id, ...options }),
          },
          args: callbackQuery.data.split(':').slice(1),
          XarV2: global.XarV2
        });
      } catch (error) {
        console.error(`Error executing onCallback for command "${commandName}":`, error);
        bot.answerCallbackQuery(callbackQuery.id, { text: "An error occurred while processing your request." });
      }
    } else {
      console.error(`No onCallback handler found for command: ${commandName}`);
      bot.answerCallbackQuery(callbackQuery.id, { text: "Invalid callback query." });
    }
  });
};

Split 🪓 the loadcommand.ts  create a new file in the handler for onCallback for my telegram bot like onStart and onReply 

//onReply.ts

 import { XarV } from "../../global";
import { messageUtils } from "../../custom/messageUtils";
import { userModel } from '../../../models/userModel';
import { threadModel } from '../../../models/threadModel';

export const handleReply = async (bot: any, msg: any) => {
  if (msg.reply_to_message) {
    const replyData = global.XarV2.onReply.get(msg.reply_to_message.message_id);
    if (replyData) {
      const command = XarV.commands.get(replyData.commandName);
      if (command && command.onReply) {
        const utils = messageUtils(bot, msg);
        try {
          await command.onReply({
            api: bot,
            args: [msg.text],
            message: utils,
            event: msg,
            threadsData: threadModel,
            threadModel,
            usersData: userModel,
            userModel,
            XarV2: global.XarV2,
            Reply: replyData
          });
        } catch (error) {
          console.error(`Error executing onReply for command "${replyData.commandName}":`, error);
          bot.sendMessage(msg.chat.id, `There was an error processing your reply for the command "${replyData.commandName}".`);
        }
        return true;
      }
    }
  }
  return false;
};      

//onStart 

 import { XarV } from "../../global";
import { messageUtils } from "../../custom/messageUtils";
import { userModel } from '../../../models/userModel';
import { threadModel } from '../../../models/threadModel';

const cooldowns = new Map();

export const handleStart = async (bot: any, msg: any, commandName: string, args: string[]) => {
  const command = XarV.commands.get(commandName) || XarV.commands.get(XarV.aliases.get(commandName));
  if (!command) {
    return;
  }

  const now = Date.now();
  const userCooldowns = cooldowns.get(msg.from.id) || {};
  const lastUsed = userCooldowns[command.config.name] || 0;
  const cooldownTime = (command.config.countDown || 5) * 1000;

  if (now - lastUsed < cooldownTime) {
    bot.sendMessage(msg.chat.id, `Please wait ${Math.ceil((cooldownTime - (now - lastUsed)) / 1000)} seconds before using this command again.`);
    return;
  }

  cooldowns.set(msg.from.id, { ...userCooldowns, [command.config.name]: now });

  const utils = messageUtils(bot, msg);
  try {
    await command.onStart({
      api: bot,
      bot,
      args,
      message: utils,
      event: msg,
      msg,
      threadsData: threadModel,
      threadModel,
      usersData: userModel,
      userModel,
      XarV2: global.XarV2
    });
  } catch (error) {
    console.error(`Error executing command "${commandName}":`, error);
    bot.sendMessage(msg.chat.id, `There was an error executing the command "${commandName}".`);
  }
};