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

Python3调用Telegram Bot API发送自定义文件名的文档

Fixing Custom Filename for Telegram Bot sendDocument in Python

Got it, let's sort out this file naming issue with your Telegram Bot! The problem with your initial attempts is that you were trying to rename the form field name (the key in the files dict) instead of specifying the actual filename for the file content itself. Telegram's API expects the field to be named document—changing that to document.txt breaks the request, which is why you got the 400 error.

Here's how to properly send your plain text content with a custom filename:

Step 1: Wrap your text content in a file-like object with a specified filename

Since you're sending plain text (doc), you can use BytesIO from the io module to turn your string into a file-like object, then attach a custom filename to it when building the files parameter.

import requests
from io import BytesIO

# Your existing variables (adjust these to your actual values)
baseurl = "https://api.telegram.org/bot"
token = "YOUR_BOT_TOKEN"
chat_id = "TARGET_CHAT_ID"
doc = "This is the plain text content I want to send as a txt file."

# Build the API endpoint URL
url = f"{baseurl}{token}/sendDocument"

# Basic payload with chat ID
payload = {'chat_id': chat_id}

# Create a file-like object from your text, and specify the custom filename
text_file = BytesIO(doc.encode('utf-8'))
files = {
    'document': ('my_custom_filename.txt', text_file, 'text/plain')
}

# Send the request
response = requests.post(url, data=payload, files=files)

# Check the response (optional, for debugging)
print(response.json())

What's happening here?

  • The files dict keeps the required field name document (this is what Telegram's API looks for).
  • The value for document is a tuple with three parts:
    1. Your custom filename (e.g., my_custom_filename.txt—this is what the recipient will see)
    2. The file-like object containing your text content
    3. The MIME type (text/plain), which tells Telegram this is a plain text file (ensures it gets the .txt extension correctly)

If you're working with a local file instead of a string

If doc was a local file you're reading from, you can simplify it by opening the file and passing it directly in the tuple:

with open("original_file.txt", "rb") as f:
    files = {
        'document': ('my_custom_name.txt', f, 'text/plain')
    }
    response = requests.post(url, data=payload, files=files)

This approach will make sure your recipient gets the file with the exact custom name you want, no more generic "document" filename!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:30:18