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

如何修复Python中Telegram Bot发送文件的ValueError错误

修复Telegram Bot发送文件时的ValueError问题

错误原因

ValueError: too many values to unpack (expected 2) 是因为requests.post的files参数格式错误。该参数要求传入字典类型,而你直接传入了打开的文件对象,导致请求解析失败。

修复方案

调整files参数为符合要求的字典格式,同时优化文件操作逻辑:

import requests

bot_token = ""
bot_chatId = ""

send_document_url = f'https://api.telegram.org/bot{bot_token}/sendDocument'
data = {
    'chat_id': bot_chatId,
    'parse_mode': 'HTML',
    'caption': 'This is my file'
}

# 使用字典格式传入files参数,键对应Telegram API的字段名
with open('/home/scrapy/diff.csv', 'rb') as file:
    files = {
        'document': ('diff.csv', file, 'text/csv')
    }
    r = requests.post(send_document_url, data=data, files=files)
    print(r.url)

print(r.json())

关键修改点

  • files参数格式:字典的键document是Telegram sendDocument接口要求的字段名,值为元组(文件名, 文件对象, MIME类型),MIME类型可选,但明确指定能提升兼容性。
  • 文件管理:用with语句自动管理文件生命周期,避免手动关闭文件的遗漏。
  • URL优化:用f-string拼接URL更简洁,移除了原URL末尾多余的?。
  • 补充依赖:添加了import requests,原代码缺失该导入会导致运行报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 14:40:33