如何通过 Telegram Bot 发送带有文件路径的照片? [英] How to send photo via Telegram Bot with file path?

查看:81
本文介绍了如何通过 Telegram Bot 发送带有文件路径的照片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

推荐答案

以下是使用 Python 中的电报 sendPhoto 端点上传文件的方法.

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)

这篇关于如何通过 Telegram Bot 发送带有文件路径的照片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆