From 8df2c47e1a4e19eff56a0d9be37b04698fada2d1 Mon Sep 17 00:00:00 2001 From: vchikalkin Date: Fri, 15 Aug 2025 18:59:45 +0300 Subject: [PATCH] refactor: improve error handling and code readability in download feature; streamline URL validation and response logic --- apps/bot/src/bot/features/download.ts | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/apps/bot/src/bot/features/download.ts b/apps/bot/src/bot/features/download.ts index 5e2cf6b..b98e0a1 100644 --- a/apps/bot/src/bot/features/download.ts +++ b/apps/bot/src/bot/features/download.ts @@ -8,7 +8,6 @@ import { Downloader } from '@tobyg74/tiktok-api-dl'; import { Composer, InputFile } from 'grammy'; const composer = new Composer(); - const feature = composer.chatType('private'); const redis = getRedisInstance(); @@ -17,17 +16,21 @@ feature.on('message:text', logHandle('download-message'), async (context) => { try { const url = context.message.text.trim(); - if (!validateTikTokUrl(url)) return context.reply(context.t('invalid_url')); + if (!validateTikTokUrl(url)) { + return context.reply(context.t('invalid_url')); + } const cachedFileId = await redis.get(url); - - if (cachedFileId) return context.replyWithVideo(cachedFileId); + if (cachedFileId) { + return context.replyWithVideo(cachedFileId); + } const { message, result } = await Downloader(url, { version: 'v3' }); + if (message) { + throw new Error(message); + } - if (message) throw new Error(message); - - const videoUrl = result?.videoHD || result?.videoSD || result?.videoWatermark; + const videoUrl = result?.videoSD || result?.videoWatermark; const imagesUrls = result?.images; if (!videoUrl && !imagesUrls?.length) { @@ -36,8 +39,8 @@ feature.on('message:text', logHandle('download-message'), async (context) => { if (result?.type === 'video' && videoUrl) { const { video } = await context.replyWithVideo(new InputFile({ url: videoUrl })); - await redis.set(url, video.file_id, 'EX', TTL); + return; } if (result?.type === 'image' && imagesUrls) { @@ -47,7 +50,6 @@ feature.on('message:text', logHandle('download-message'), async (context) => { } } catch (error) { context.logger.error(error); - return context.reply(context.t('generic')); } });