DEV Community

Fabian Anguiano
Fabian Anguiano

Posted on

How to send PDF's with Telegram.

In this article, we will cover how to send a PDF via telegram.
NOTE: This guide assumes you have an API token from Telegram.

Here is the code so you can see it before we start.

import requests

def send_pdf(bot_token, chat_id, pdf_path):
    """
    Send a PDF document to a specific chat using Telegram Bot API.

    :param bot_token: str - Your Telegram bot token
    :param chat_id: str - Your chat id
    :param pdf_path: str - The path to the PDF file you want to send
    """
    method = "sendDocument"
    url = f"https://api.telegram.org/bot{bot_token}/{method}"
    files = {'document': open(pdf_path, 'rb')}
    data = {'chat_id': chat_id}
    response = requests.post(url, files=files, data=data)
    return response.json()  # Returns the result as a JSON object

# Call the function and print the result
result = send_pdf(bot_token, chat_id, pdf_path)
print(result)
Enter fullscreen mode Exit fullscreen mode

Here is a breakdown.

The Function Components

  • pdf_path:

    • Description: This specifies the location of the PDF file you want to send.
    • Usage: Replace 'Invoices1.pdf' with the path to your document.
  • bot_token:

    • Description: This is your unique token for interacting with the Telegram bot.
    • Usage: Replace YOUR_BOT_TOKEN with the token you received from BotFather.
  • chat_id:

    • Description: This is the identifier for the chat where you want to send your PDF.
    • Usage: Replace YOUR_CHAT_ID with the desired chat ID.

Once you set up your parameters, you move on to making the actual request to send the pdf.

Making the Request

Inside the function, the code constructs and sends an HTTP request to the Telegram API:

  • Method: method = "sendDocument"

    • This specifies the action we want our bot to perform - sending a document.
  • Constructing the URL:

    • url = f"https://api.telegram.org/bot{bot_token}/{method}"
    • This dynamically creates the request URL using your bot's token.
  • Preparing the File:

    • files = {'document': open(pdf_path, 'rb')}
    • This opens your PDF in binary read mode, ready for transmission.
  • Sending the Request:

    • response = requests.post(url, files=files, data=data)
    • This sends the file to the specified chat via your bot.

Execution

result = send_pdf(bot_token, chat_id, pdf_path)
print(result)

Once you execute, you will know pretty quickly if the PDF has been sent ! Feel free to comment or contact me with any questions.

You can contact me at X

Top comments (0)