How to send photo via Telegram Bot with file path?

穿精又带淫゛_ 提交于 2020-06-17 09:43:29

问题


I am trying to send a photo through my Telegram bot, but am getting an error. I have the file path of the photo on my computer. Maybe I am not putting the file path in correctly. The error I get is:

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape`. 

Which is referring to right before the path name. This is the code I have:

import requests
import json

bot_token = 'XXXXXX'
chat_id = "-100YYYYYY"
file = "C:\Users\name\OneDrive\Desktop\Capture.PNG"

message = ('https://api.telegram.org/bot'+ bot_token + '/sendPhoto?chat_id=' 
           + chat_id + 'photo=' + file)
send = requests.get(message)

回答1:


Here is how you should upload file using the telegram sendPhoto endpoint in python.

import requests
import json

bot_token = 'BOT TOKEN'
chat_id = "CHAT ID"
file = r"C:\Users\name\OneDrive\Desktop\Capture.PNG"

files = {
    'photo': open(file, 'rb')
}

message = ('https://api.telegram.org/bot'+ bot_token + '/sendPhoto?chat_id=' 
           + chat_id)
send = requests.post(message, files = files)


来源:https://stackoverflow.com/questions/61463102/how-to-send-photo-via-telegram-bot-with-file-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!