Search code examples
pythontelegramtelegram-botsendfile

How to send some files with telegram bot in python


I'm trying to upload the outcomes of my code (they are images) in a group with a Telegram bot.

I've tried:

import requests
import numpy as np

paths=np.array([])
for z in range(8):
    paths=np.append(paths,str(f"path\\{z}.jpg"))

url="https://api.telegram.org/bot<<my-bot-http-token>>/senddocument?chat_id=<<chat-id>>"
for path in paths:
    files={'document':open(path,'rb')}
    resp=requests.post(url,files=files)

It works but it sends the files separately and I want to group them then send.


Solution

  • You're using the sendDocument method, however, for grouped files/image, you'll need sendMediaGroup with an array of media


    Here a minimum reproducable example to send a group of local photo's:

    import json
    import requests
    
    chat_id = 1234567
    TOKEN = '85916...the-rest-of-your-token'
    
    data = {
        "chat_id": chat_id,
        "media": json.dumps([
            {"type": "photo", "media": "attach://photo1.png"},
            {"type": "photo", "media": "attach://photo2.png"}
        ])
    }
    
    files = {
        "photo1.png" : open("./photo1.png", 'rb'),
        "photo2.png" : open("./photo2.png", 'rb')
    }
    
    temp = requests.post("https://api.telegram.org/bot" + TOKEN + "/sendMediaGroup", data=data, files=files)
    
    print(temp.json())
    

    Result screenshot:

    enter image description here