我试图用 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)
我在您的代码片段中发现了几个问题:
path
已经是绝对路径,因此将其与当前目录连接将给出无效路径'rb'
打开,而不是 'r'
content
变量,但从不使用该变量bot.send_message
的调用发生在上下文管理器 (with open(…)
) 之外,因此 input_file
是该行上的 filled 文件,并且 PTB 无法读取其内容。另请查看 PTB wiki 中有关发送文件的部分。
免责声明:我目前是
python-telegram-bot
的维护者
这可能会有所帮助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'))