Python Telegram Bot - 如何将 JSON response.content 作为 PDF 文件发送

Python Telegram Bot - How to send JSON response.content as PDF file

使用会话机器人,我需要点击 URL returns response.content JSON 中的 PDF 文件。我想将此文件直接发送给用户而不将其保存在服务器上。如何才能做到这一点? 示例代码:

response = requests.get(url)  
pdf = open("pdffile.pdf", 'wb')  
pdf.write(response.content)  
pdf.close()  
file = "pdffile.pdf"
update.message.reply_document(document=open(file, 'rb'))

我不想执行写入操作

正如我在上面的评论中所暗示的,您可以将字节流传递给 send_document。这是基于您的代码片段的最小示例(插入您的机器人令牌和聊天 ID):

import requests
from telegram import Bot

bot = Bot("TOKEN")
response = requests.get('https://python-telegram-bot.readthedocs.io/_/downloads/en/stable/pdf/')
bot.send_document(YOUR_CHAT_ID, document=response.content, filename='python-telegram-bot.pdf')

注意我传递了filename参数。这允许您提供将显示给收件人的自定义文件名。


免责声明:我目前是 python-telegram-bot.

的维护者