bot-me / src /utils /botUtils.ts
Mohammed Foud
all
8cb18a7
import { Context } from 'telegraf';
import { BotContext } from '../bots/types/botTypes';
import { createLogger } from './logger';
const logger = createLogger('BotUtils');
// Map to store bot token to bot ID mapping
const botTokenToIdMap = new Map<string, string>();
/**
* Extracts bot ID from a bot token
* @param token The bot token to extract ID from
* @returns The bot ID
*/
export function getBotIdFromToken(token: string): string {
// Check if we already have this mapping cached
if (botTokenToIdMap.has(token)) {
return botTokenToIdMap.get(token)!;
}
// Extract bot ID from token (format: <bot_id>:<random_string>)
const botId = token.split(':')[0];
// Cache the mapping
botTokenToIdMap.set(token, botId);
return botId;
}
/**
* Gets bot token from context
* @param ctx The Telegraf context
* @returns The bot token or undefined if not found
*/
export function getBotTokenFromContext(ctx: BotContext): string | undefined {
try {
// Try to get token from bot instance
return (ctx as any).telegram?.token;
} catch (error) {
logger.error('Error getting bot token from context:', error);
return undefined;
}
}
/**
* Saves a bot token to ID mapping
* @param token The bot token
* @param botId The bot ID
*/
export function saveBotTokenMapping(token: string, botId: string): void {
botTokenToIdMap.set(token, botId);
logger.info(`Saved bot token mapping for bot ID: ${botId}`);
}
/**
* Gets bot ID from context
* @param ctx The Telegraf context
* @returns The bot ID or undefined if not found
*/
export function getBotIdFromContext(ctx: BotContext): string | undefined {
try {
// First try to get from botData if available
if (ctx.botData?.id) {
return ctx.botData.id;
}
// Then try to get from token
const token = getBotTokenFromContext(ctx);
if (token) {
return getBotIdFromToken(token);
}
return undefined;
} catch (error) {
logger.error('Error getting bot ID from context:', error);
return undefined;
}
}
/**
* Validates a bot token format
* @param token The bot token to validate
* @returns boolean indicating if the token is valid
*/
export function isValidBotToken(token: string): boolean {
if (!token) return false;
// Check if token follows the format: <bot_id>:<random_string>
const parts = token.split(':');
if (parts.length !== 2) return false;
// Check if bot_id is numeric
const botId = parts[0];
if (!/^\d+$/.test(botId)) return false;
// Check if random_string is not empty
if (!parts[1]) return false;
return true;
}
/**
* Clears the bot token to ID mapping cache
*/
export function clearBotTokenCache(): void {
botTokenToIdMap.clear();
logger.info('Cleared bot token mapping cache');
}