How to send an image from a telegram bot

前端 未结 4 1869
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-22 13:17

I have my bot working by now, but the thing is it can only send text. I have seen in the Bot API there are functions to send photos, videos... but I can\'t get it to work. S

4条回答
  •  半阙折子戏
    2020-12-22 14:10

    I have included two functions, one is good for sending local images, the other one is good for sending remote images.

    def sendImage():
        url = "https://api.telegram.org/bot/sendPhoto";
        files = {'photo': open('/path/to/img.jpg', 'rb')}
        data = {'chat_id' : "YOUR_CHAT_ID"}
        r= requests.post(url, files=files, data=data)
        print(r.status_code, r.reason, r.content)
    
    def sendImageRemoteFile(img_url):
        url = "https://api.telegram.org/bot/sendPhoto";
        remote_image = requests.get(img_url)
        photo = io.BytesIO(remote_image.content)
        photo.name = 'img.png'
        files = {'photo': photo}
        data = {'chat_id' : "YOUR_CHAT_ID"}
        r= requests.post(url, files=files, data=data)
        print(r.status_code, r.reason, r.content)
    

提交回复
热议问题