telegram-node-bot文件上传指南:三种方式发送照片、视频和文档
telegram-node-bot文件上传指南:三种方式发送照片、视频和文档
【免费下载链接】telegram-node-botNode module for creating Telegram bots.项目地址: https://gitcode.com/gh_mirrors/te/telegram-node-bot
telegram-node-bot是一个功能强大的Node.js模块,专门用于创建Telegram机器人。本文将详细介绍如何使用telegram-node-bot实现文件上传功能,涵盖发送照片、视频和文档的三种不同方式。无论你是新手还是有经验的开发者,这篇完整指南都将帮助你快速掌握telegram-node-bot的文件上传技巧。
📁 为什么需要文件上传功能?
在Telegram机器人开发中,文件上传是核心功能之一。无论是发送图片、视频、音频还是文档,telegram-node-bot都提供了简单易用的API。通过本文,你将学习到:
- 使用文件ID快速发送已存在的文件
- 从本地文件系统上传文件
- 通过URL远程发送文件
- 处理不同类型文件的最佳实践
🔧 准备工作:安装与基础配置
首先,确保你已经安装了telegram-node-bot模块:
npm install --save telegram-node-bot创建基础机器人结构:
const Telegram = require('telegram-node-bot') const TelegramBaseController = Telegram.TelegramBaseController const TextCommand = Telegram.TextCommand const tg = new Telegram.Telegram('YOUR_BOT_TOKEN')📤 方法一:使用文件ID发送文件(最快方式)
文件ID是Telegram服务器上文件的唯一标识符。当你收到用户发送的文件或之前发送过文件时,Telegram会返回一个文件ID,你可以重复使用这个ID发送相同的文件。
发送照片示例
class FileUploadController extends TelegramBaseController { async photoHandler($) { // 使用文件ID发送照片 await $.sendPhoto('AgACAgUAAxkBAAIB...') // 替换为实际的文件ID // 或者使用InputFile.byId()方法 const InputFile = require('telegram-node-bot').InputFile await $.sendPhoto(InputFile.byId('AgACAgUAAxkBAAIB...')) } get routes() { return { '/sendphoto': 'photoHandler' } } }发送视频示例
class VideoUploadController extends TelegramBaseController { async videoHandler($) { // 使用文件ID发送视频 await $.sendVideo('BAACAgUAAxkBAAIB...') // 可选参数:添加标题和时长 await $.sendVideo('BAACAgUAAxkBAAIB...', { caption: '这是一个有趣的视频!🎬', duration: 120 }) } get routes() { return { '/sendvideo': 'videoHandler' } } }发送文档示例
class DocumentUploadController extends TelegramBaseController { async documentHandler($) { // 使用文件ID发送文档 await $.sendDocument('BQACAgUAAxkBAAIB...') // 可选参数:添加文件名和缩略图 await $.sendDocument('BQACAgUAAxkBAAIB...', { caption: '重要文档请查收 📄', disable_notification: true }) } get routes() { return { '/senddoc': 'documentHandler' } } }💾 方法二:从本地文件系统上传文件
这是最常用的文件上传方式,允许你发送本地计算机上的文件。
发送本地照片
class LocalFileController extends TelegramBaseController { async localPhotoHandler($) { const InputFile = require('telegram-node-bot').InputFile // 方式一:使用InputFile.byFilePath() await $.sendPhoto(InputFile.byFilePath('./images/photo.jpg')) // 方式二:使用对象格式 await $.sendPhoto({ path: './images/photo.jpg' }) // 添加照片描述和可选参数 await $.sendPhoto(InputFile.byFilePath('./images/photo.jpg'), { caption: '美丽的风景照片 🌄', parse_mode: 'HTML' }) } get routes() { return { '/localphoto': 'localPhotoHandler' } } }发送本地视频
class LocalVideoController extends TelegramBaseController { async localVideoHandler($) { const InputFile = require('telegram-node-bot').InputFile // 发送本地视频文件 await $.sendVideo(InputFile.byFilePath('./videos/demo.mp4'), { caption: '演示视频 🎥', supports_streaming: true, width: 1280, height: 720 }) } get routes() { return { '/localvideo': 'localVideoHandler' } } }发送本地文档
class LocalDocumentController extends TelegramBaseController { async localDocumentHandler($) { const InputFile = require('telegram-node-bot').InputFile // 发送PDF文档 await $.sendDocument(InputFile.byFilePath('./docs/report.pdf'), { caption: '月度报告 📊', disable_content_type_detection: false }) // 发送Excel文件 await $.sendDocument(InputFile.byFilePath('./data/sales.xlsx'), { caption: '销售数据表格 📈' }) } get routes() { return { '/localdoc': 'localDocumentHandler' } } }🌐 方法三:通过URL远程发送文件
telegram-node-bot支持直接从URL发送文件,这对于发送网络上的图片或文档非常有用。
发送远程照片
class RemoteFileController extends TelegramBaseController { async remotePhotoHandler($) { const InputFile = require('telegram-node-bot').InputFile // 方式一:使用InputFile.byUrl() await $.sendPhoto( InputFile.byUrl( 'https://example.com/images/landscape.jpg', 'landscape.jpg' ) ) // 方式二:使用对象格式 await $.sendPhoto({ url: 'https://example.com/images/landscape.jpg', filename: 'landscape.jpg' }) // 添加可选参数 await $.sendPhoto( InputFile.byUrl('https://example.com/images/sunset.jpg', 'sunset.jpg'), { caption: '日落美景 🌅', disable_notification: true } ) } get routes() { return { '/remotephoto': 'remotePhotoHandler' } } }发送远程视频
class RemoteVideoController extends TelegramBaseController { async remoteVideoHandler($) { const InputFile = require('telegram-node-bot').InputFile // 发送远程视频 await $.sendVideo( InputFile.byUrl( 'https://example.com/videos/tutorial.mp4', 'tutorial.mp4' ), { caption: '教程视频 📺', duration: 300, width: 1920, height: 1080 } ) } get routes() { return { '/remotevideo': 'remoteVideoHandler' } } }发送远程文档
class RemoteDocumentController extends TelegramBaseController { async remoteDocumentHandler($) { const InputFile = require('telegram-node-bot').InputFile // 发送远程PDF文档 await $.sendDocument( InputFile.byUrl( 'https://example.com/docs/manual.pdf', 'user_manual.pdf' ), { caption: '用户手册 📖', disable_web_page_preview: true } ) } get routes() { return { '/remotedoc': 'remoteDocumentHandler' } } }🔄 支持的文件类型和参数
telegram-node-bot支持多种文件类型,每种类型都有特定的参数:
照片上传参数
caption: 照片描述文字parse_mode: 解析模式(Markdown或HTML)disable_notification: 静默发送reply_to_message_id: 回复特定消息
视频上传参数
duration: 视频时长(秒)width: 视频宽度height: 视频高度supports_streaming: 是否支持流式传输thumb: 缩略图文件ID
文档上传参数
caption: 文档描述disable_content_type_detection: 禁用内容类型检测thumb: 缩略图文件ID
🚀 高级技巧:组合使用三种方式
在实际项目中,你可能需要根据不同的场景选择不同的上传方式。以下是一个综合示例:
class AdvancedUploadController extends TelegramBaseController { async uploadHandler($) { const InputFile = require('telegram-node-bot').InputFile const fileType = $.message.text.split(' ')[1] switch(fileType) { case 'id': // 使用文件ID(最快) await $.sendPhoto('AgACAgUAAxkBAAIB...') break case 'local': // 使用本地文件 await $.sendDocument(InputFile.byFilePath('./files/data.csv')) break case 'remote': // 使用远程URL await $.sendVideo({ url: 'https://cdn.example.com/video.mp4', filename: 'video.mp4' }) break default: await $.sendMessage('请指定上传方式:id、local 或 remote') } } get routes() { return { '/upload :type': 'uploadHandler' } } }⚡ 性能优化建议
- 优先使用文件ID:文件ID方式最快,因为不需要重新上传文件
- 本地文件缓存:对于经常发送的文件,可以先上传一次获取文件ID,然后重复使用
- URL文件处理:telegram-node-bot会自动下载URL文件并上传到Telegram
- 错误处理:始终添加错误处理代码
class SafeUploadController extends TelegramBaseController { async safeUploadHandler($) { try { await $.sendPhoto(InputFile.byFilePath('./images/photo.jpg'), { caption: '上传成功!✅' }) } catch (error) { console.error('文件上传失败:', error) await $.sendMessage('抱歉,文件上传失败,请稍后重试。❌') } } get routes() { return { '/safeupload': 'safeUploadHandler' } } }📝 实际应用场景
场景一:图片分享机器人
class ImageBotController extends TelegramBaseController { async imageHandler($) { const command = $.message.text if (command.includes('cat')) { await $.sendPhoto(InputFile.byUrl( 'https://example.com/cats/random.jpg', 'cat.jpg' ), { caption: '可爱的猫咪!🐱' }) } else if (command.includes('dog')) { await $.sendPhoto(InputFile.byFilePath('./images/dogs/dog1.jpg'), { caption: '忠诚的狗狗!🐶' }) } } get routes() { return { '/image :type': 'imageHandler' } } }场景二:文档管理机器人
class DocumentBotController extends TelegramBaseController { async documentHandler($) { // 获取用户上传的文件ID const fileId = $.message.document.file_id // 保存文件ID到数据库 await saveFileIdToDatabase(fileId, $.message.document.file_name) // 确认收到文件 await $.sendMessage(`已收到文件:${$.message.document.file_name}`) // 稍后可以重复发送该文件 // await $.sendDocument(fileId) } get routes() { return { 'documentCommand': 'documentHandler' } } }🔍 调试技巧
- 查看文件信息:使用
$.message.document、$.message.photo等属性获取文件详情 - 日志记录:记录文件上传过程以便调试
- 文件大小限制:注意Telegram的文件大小限制(照片20MB,视频50MB,文档50MB)
🎯 总结
telegram-node-bot提供了三种灵活的文件上传方式:
- 文件ID方式:最快速,适合重复发送相同文件
- 本地文件方式:最常用,适合发送本地文件
- URL方式:最方便,适合发送网络文件
通过本文的指南,你应该已经掌握了telegram-node-bot文件上传的核心功能。记住查看lib/api/InputFile.js和lib/api/TelegramApi.js文件了解底层实现,以及lib/mvc/Scope.js中的Scope类方法。
现在就开始构建你的文件上传功能吧!如果你遇到任何问题,记得查阅官方文档或社区支持。🚀
【免费下载链接】telegram-node-botNode module for creating Telegram bots.项目地址: https://gitcode.com/gh_mirrors/te/telegram-node-bot
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
