使用python将pdf文件上传到电报机器人

问题描述 投票:0回答:2

我试图用 python 将 pdf 文件上传到电报机器人,但它不起作用。我的错误在哪里?

def textbooks(update,context):
    path = r"C:\Users\Ya'we\Downloads\Python Practice Book (en)(1).pdf"

    with open(os.path.join(os.path.dirname(__file__), path), 'r') as input_file:
        content = input_file.read()
    chat_id=update.effective_chat.id
    return context.bot.send_document(chat_id, input_file)
python python-telegram-bot
2个回答
2
投票

我在您的代码片段中发现了几个问题:

  1. path
    已经是绝对路径,因此将其与当前目录连接将给出无效路径
  2. 文件应以
    'rb'
    打开,而不是
    'r'
  3. 您将文件内容读入
    content
    变量,但从不使用该变量
  4. bot.send_message
    的调用发生在上下文管理器 (
    with open(…)
    ) 之外,因此
    input_file
    是该行上的 filled 文件,并且 PTB 无法读取其内容。

另请查看 PTB wiki 中有关发送文件的部分


免责声明:我目前是

python-telegram-bot

的维护者

0
投票

这可能会有所帮助https://github.com/python-telegram-bot/python-telegram-bot/wiki/Working-with-Files-and-Media

参考上面的链接,如果您更改代码如下,它应该可以工作。

def textbooks(update,context):
    path = r"C:\Users\Ya'we\Downloads\Python Practice Book (en)(1).pdf"
    chat_id=update.effective_chat.id
    return context.bot.send_document(chat_id,document=open(os.path.join(os.path.dirname(__file__), path), 'rb'))
© www.soinside.com 2019 - 2024. All rights reserved.