//loadCommands.ts import { XarV } from "../global"; import… · The Chat Archive
Explore //loadCommands.ts import { XarV } from "../global"; import { readdirSync } from "fs";… Save Share Download ▾ Report//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;
code Copy code
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);
Show full message · 181 lines Assistant2024-09-26 15:59 UTC Copy response
To create a separate handler for onCallback similar to onStart and onReply, you will need to create a new file (let's call it onCallback.ts) in the handler directory. Here's how you can implement it:
Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language en
Conversation date Sep 26, 2024
Added to archive Nov 16, 2026
ID 01m7h41vyd326cv82vq17g958wSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 23a618ec384b1cc05921bc27d2d60dd8
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
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
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;
};
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}".);
}
};
New File: onCallback.ts typescript Copy code
import { XarV } from "../../global";
import { messageUtils } from "../../custom/messageUtils";
export const handleCallback = async (bot: any, callbackQuery: any) => {
const [commandName, ...args] = callbackQuery.data.split(':');
const command = XarV.commands.get(commandName);
if (command && command.onCallback) {
try {
const utils = messageUtils(bot, callbackQuery.message);
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,
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." });
}
};
Modify loadCommands.ts to Use onCallback Now, update your loadCommands.ts to use the new handleCallback function:
typescript Copy code
import { handleCallback } from "./handler/onCallback";
// Existing code...
// Add callback query handler
bot.on("callback_query", async (callbackQuery: any) => {
await handleCallback(bot, callbackQuery);
});
This refactoring moves the onCallback handling logic into its own module for better separation of concerns and maintainability, similar to how you have onReply and onStart handlers.
Copy first response
Not yet included in a published release.