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

如何用Python telebot模块下载Telegram频道文件?代码问题排查

问题解答:用Python telebot从Telegram频道下载文件

首先明确:可以使用telebot模块从Telegram频道下载文件,你的代码存在几个错误导致文件未生成,具体如下:

代码中的错误点

  • 变量名不匹配:你通过info = bot.get_file(id)获取了文件信息,但后续调用bot.download_file时误用了file_info.file_path,正确的变量名应为info.file_path。
  • 下载数据处理错误:bot.download_file返回的是直接可写入的字节数据,而非带content属性的对象,无需调用.content即可写入文件。
  • 目录存在性问题:如果directory对应的目录不存在,os.path.join不会自动创建目录,写入文件时会抛出异常,需提前确保目录存在。

修正后的代码示例

import os
from colorama import Fore
import telebot

# 假设bot实例和directory变量已正确初始化
@bot.message_handler(content_types=['document'])
def main(message):
    if message.document.file_name.startswith("schedule"):
        print(f"{Fore.GREEN}got this file: {message.document.file_name}")

        file_id = message.document.file_id
        file_info = bot.get_file(file_id)

        downloaded_file = bot.download_file(file_info.file_path)
        path = os.path.join(directory, message.document.file_name)
        
        # 确保目标目录存在,不存在则创建
        os.makedirs(directory, exist_ok=True)

        with open(path, 'wb') as channel_file:
            channel_file.write(downloaded_file)

额外注意:机器人必须是目标频道的管理员,且拥有读取消息的权限,否则无法获取频道内的文件消息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 05:12:38