Python 我不能向电报机器人用户发送消息,但我自己可以
为什么我不能向我的机器人用户发送消息Python 我不能向电报机器人用户发送消息,但我自己可以,python,telegram-bot,Python,Telegram Bot,为什么我不能向我的机器人用户发送消息 filename = 'a.png' url = "https://api.telegram.org/botxxxxx:yyyyyyyyyyyyy/sendPhoto"; files = {'photo': open(filename, 'rb')} data = {'chat_id': "538087xx"} r = requests.post(url, files=files, data=data) print(r.status_code, r.re
filename = 'a.png'
url = "https://api.telegram.org/botxxxxx:yyyyyyyyyyyyy/sendPhoto";
files = {'photo': open(filename, 'rb')}
data = {'chat_id': "538087xx"}
r = requests.post(url, files=files, data=data)
print(r.status_code, r.reason, r.content)
data = {'chat_id': "642201xx"}
r = requests.post(url, files=files, data=data)
print(r.status_code, r.reason, r.content)
data = {'chat_id': "350225xx"}
r = requests.post(url, files=files, data=data)
print(r.status_code, r.reason, r.content)
我正在尝试向3个用户发送消息,第一个是我,机器人所有者,我可以接收消息。2其他帐户已向bot发送消息。但结果是:
(200, 'OK', '{"ok":true,"result":{"message_id":77,"from":{"id":5258785xx,"is_bot":true,"first_name":"anal_bot","username":"rojandco_bot"},"chat":{"id":538087xx,"first_name":"Ehsan","username":"Shirzadi","type":"private"},"date":1542626038,"photo":[{"file_id":"AgADBAADeqwxG0-KmVNFxlFtWWBr7AQvuhoABG2shK_JcTywFuQEAAEC","file_size":1084,"width":90,"height":63},{"file_id":"AgADBAADeqwxG0-KmVNFxlFtWWBr7AQvuhoABKqN07Vwmbw_F-QEAAEC","file_size":12199,"width":320,"height":224},{"file_id":"AgADBAADeqwxG0-KmVNFxlFtWWBr7AQvuhoABCOVGKfhnnt_GeQEAAEC","file_size":49836,"width":800,"height":561},{"file_id":"AgADBAADeqwxG0-KmVNFxlFtWWBr7AQvuhoABAyOV-TH27bRGOQEAAEC","file_size":99617,"width":1280,"height":898}]}}')
(400, 'Bad Request', '{"ok":false,"error_code":400,"description":"Bad Request: file must be non-empty"}')
(400, 'Bad Request', '{"ok":false,"error_code":400,"description":"Bad Request: file must be non-empty"}')
使用打开第四行的文件
files = {'photo': open(filename, 'rb')}
第一个request.post
调用可能会关闭文件句柄,从而使第二个和第三个request.post
无法使用它
您发布的错误消息包含您需要的信息。要解决此问题,只需在每次发布数据之前重新打开文件即可
编辑:
Wombatz是正确的请求。post
读取到文件末尾
以下是您如何查找文件开头的内容:
files['photo'].seek(0)
问题是,
请求.post
读取文件,但没有将其重置到可以看到的起始位置:在第159行中,读取发生
因此,您的第一个post
可以工作,但所有后续请求都会向电报发送一个空文件。事实上,这正是电报告诉您的“错误请求:文件必须非空”
:您发送的是一个空文件
这意味着,为了多次发送同一个文件,您可以重新打开该文件或查找文件的开头,或者在读取文件时,将文件内容直接传递给请求
(可能是三种方法中最好的一种),如下所示:
with open(filename, 'rb') as photo:
files = {'photo': photo.read()} # note that we actually read() the file here
for user in all_the_users_you_want_to_send_the_file_to:
requests.post(url, files=files, ...)
请注意,这是可行的,因为请求
也接受字符串而不是类似文件的对象。像这样,文件只读取一次,这可能会更快,具体取决于文件大小。(有关更多详细信息,请参阅)
还要注意,在读取或写入文件时,确实应该使用with
语句
请求
完成后不关闭文件。在这种情况下,您将看到如下错误消息
ValueError:读取已关闭的文件