You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Node.js开发的Telegram Bot中发送自定义文件名的文档?

Telegram Bot发送文件时自定义文件名的实现方法

不管你使用哪款Python Telegram Bot开发库,核心都是通过指定filename参数来覆盖文件原有名称,以下是两款常用库的实现示例:

一、python-telegram-bot 库

发送本地文件

from telegram import Bot
from telegram.error import TelegramError

bot = Bot(token="你的Bot Token")
file_path = "./index.pdf"

try:
    # 用filename参数指定用户看到的文件名
    bot.send_document(chat_id=目标用户ID, document=open(file_path, 'rb'), filename="myfilename.pdf")
except TelegramError as e:
    print(f"发送失败: {e}")

发送API获取的字节流文件

import requests
from telegram import Bot

bot = Bot(token="你的Bot Token")
api_file_url = "你获取index.pdf的API地址"
response = requests.get(api_file_url)

if response.status_code == 200:
    # 直接传入字节内容,同时指定自定义文件名
    bot.send_document(chat_id=目标用户ID, document=response.content, filename="myfilename.pdf")

二、pyTelegramBotAPI 库

发送本地文件

import telebot

bot = telebot.TeleBot("你的Bot Token")

with open('./index.pdf', 'rb') as file:
    bot.send_document(目标用户ID, file, filename="myfilename.pdf")

发送API获取的字节流文件

import requests
import telebot

bot = telebot.TeleBot("你的Bot Token")
api_file_url = "你获取index.pdf的API地址"
response = requests.get(api_file_url)

if response.status_code == 200:
    bot.send_document(目标用户ID, response.content, filename="myfilename.pdf")

注意:所有发送文件的核心方法(如send_document)都支持filename参数,设置后用户端显示的文件名就是你指定的自定义名称,和原文件的名称无关。

内容的提问来源于stack exchange,提问作者Ketan Rathod

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 18:28:01