Search code examples
python-telegram-bot

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


With the conversational Bot, I need to hit a URL which returns a PDF file in response.content JSON. I want to send this file directly to the User without saving it on the server. How can this be done? Sample Code:

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'))

I don't want to perfrom the write operation


Solution

  • As hinted in my comments above, you can pass a bytes stream to send_document. Here is minimal example based on your code snippet (plug in your bot token and your chat 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')
    

    Note that I passed the filename parameter. This allows you to give a custom filename that will be displayed for the recipient.


    Disclaimer: I'm currently the maintainer of python-telegram-bot.