使用youtube-dl开发Telegram Bot时如何获取视频响应并发送给用户
问题1:变量作用域报错(ReferenceError: output is not defined)
你同时混用了await和.then异步写法:
.then回调函数中的output是仅在回调内部生效的局部变量,外部代码无法访问- 你在
.then中仅执行了console.log(output)没有返回值,导致await youtubedl(...)最终返回的video变量也是undefined
这就是你第一个报错的直接原因。
问题2:output内容不是视频文件路径
youtube-dl-exec默认返回的是命令行执行的全部日志内容,也就是你收到的下载进度、目标文件名等文本内容,不是下载后的视频本地路径:
- 你拿日志字符串调用
sendMessage,自然用户就收到了下载日志文本 - 你拿日志字符串调用
sendVideo,Telegram API会默认把传入的字符串当成HTTP URL解析,自然就报invalid file HTTP URL specified的错误。
修复方案
- 去掉冗余的
.then写法,直接用await接收返回值 - 给youtube-dl指定输出路径,避免从日志中解析文件名的额外操作
- 调用
sendVideo时传入本地视频文件的可读流或者绝对路径 - 补充异常捕获,避免未处理的Promise报错
修改后的代码参考:
const telegramApi = require("node-telegram-bot-api"); const token = "myApi"; const fs = require("fs"); const path = require("path"); const youtubedl = require("youtube-dl-exec"); const bot = new telegramApi(token, { polling: true }); const start = () => { bot.on("message", async (msg) => { const text = msg.text; const chatId = msg.chat.id; const mode = "youtube"; try { if (text === "/start") { await bot.sendSticker( chatId, "https://tlgrm.ru/_/stickers/b50/063/b5006369-8faa-44d7-9f02-1ca97d82cd49/1.webp" ); await bot.sendMessage(chatId, "Пошла жара..."); return; } if (mode === "youtube") { console.log("Test video sending"); // 自定义输出文件名,避免特殊字符导致路径错误 const outputPath = path.resolve(__dirname, `./${Date.now()}.mp4`); // 执行下载,指定输出路径 await youtubedl(text, { noWarnings: true, preferFreeFormats: true, o: outputPath // o参数指定输出文件路径 }); // 发送本地视频文件 await bot.sendVideo(chatId, fs.createReadStream(outputPath), { caption: "视频下载完成" }); // 可选:发送完成后删除本地文件,避免占用磁盘空间 fs.unlinkSync(outputPath); } } catch (e) { console.error(e); await bot.sendMessage(chatId, "处理失败,请稍后重试"); } }); }; start();
内容的提问来源于stack exchange,提问作者JOKER
相关产品推荐
相关产品推荐

