如何通过带有文件路径的Telegram Bot发送照片?

时间:2020-04-27 16:02:45

标签: python telegram telegram-bot python-telegram-bot

我正在尝试通过Telegram机器人发送照片,但出现错误。我的计算机上有照片的文件路径。也许我没有正确放置文件路径。我得到的错误是:

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

指的是路径名之前的位置。这是我的代码:

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)

2 个答案:

答案 0 :(得分:2)

这是您应该如何使用python中的电报sendPhoto端点上载文件的方法。

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)

答案 1 :(得分:-1)

在回答这个问题时,我使用了上面的代码,但是图像质量很差,我无法清楚地理解图像内容。图片是我的笔记本电脑屏幕的屏幕截图,分辨率为1080p