问题
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