|
|
import { Context } from 'telegraf'; |
|
|
import { BotContext } from '../bots/types/botTypes'; |
|
|
import { createLogger } from './logger'; |
|
|
|
|
|
const logger = createLogger('BotUtils'); |
|
|
|
|
|
|
|
|
const botTokenToIdMap = new Map<string, string>(); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export function getBotIdFromToken(token: string): string { |
|
|
|
|
|
if (botTokenToIdMap.has(token)) { |
|
|
return botTokenToIdMap.get(token)!; |
|
|
} |
|
|
|
|
|
|
|
|
const botId = token.split(':')[0]; |
|
|
|
|
|
|
|
|
botTokenToIdMap.set(token, botId); |
|
|
|
|
|
return botId; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export function getBotTokenFromContext(ctx: BotContext): string | undefined { |
|
|
try { |
|
|
|
|
|
return (ctx as any).telegram?.token; |
|
|
} catch (error) { |
|
|
logger.error('Error getting bot token from context:', error); |
|
|
return undefined; |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export function saveBotTokenMapping(token: string, botId: string): void { |
|
|
botTokenToIdMap.set(token, botId); |
|
|
logger.info(`Saved bot token mapping for bot ID: ${botId}`); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export function getBotIdFromContext(ctx: BotContext): string | undefined { |
|
|
try { |
|
|
|
|
|
if (ctx.botData?.id) { |
|
|
return ctx.botData.id; |
|
|
} |
|
|
|
|
|
|
|
|
const token = getBotTokenFromContext(ctx); |
|
|
if (token) { |
|
|
return getBotIdFromToken(token); |
|
|
} |
|
|
|
|
|
|
|
|
return undefined; |
|
|
} catch (error) { |
|
|
logger.error('Error getting bot ID from context:', error); |
|
|
return undefined; |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export function isValidBotToken(token: string): boolean { |
|
|
if (!token) return false; |
|
|
|
|
|
|
|
|
const parts = token.split(':'); |
|
|
if (parts.length !== 2) return false; |
|
|
|
|
|
|
|
|
const botId = parts[0]; |
|
|
if (!/^\d+$/.test(botId)) return false; |
|
|
|
|
|
|
|
|
if (!parts[1]) return false; |
|
|
|
|
|
return true; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export function clearBotTokenCache(): void { |
|
|
botTokenToIdMap.clear(); |
|
|
logger.info('Cleared bot token mapping cache'); |
|
|
} |