我无法向电报机器人用户发送消息,但我自己

时间:2018-11-19 11:15:39

标签: 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.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个帐户已经向机器人发送了一条消息。但结果是:

(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"}')

2 个答案:

答案 0 :(得分:2)

问题是requests.post读取了文件,但没有将其重置为起始位置here:在159行中发生了读取。

因此,您的第一个post可以正常工作,但是所有后续请求都会将 empty 文件发送到电报。实际上,电报是用"Bad Request: file must be non-empty"告诉您的:您正在发送一个空文件。

这意味着,为了多次发送同一文件,您可以重新打开文件或搜索到文件的开头,或者-始终在读取文件时-将文件的内容直接传递给{{ 1}}(可能是三个中的最佳解决方案):

requests

请注意,这是可行的,因为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, ...) 也接受字符串而不是类似文件的对象。像这样,该文件只能读取一次,这可能会更快,具体取决于文件大小。 (有关更多详细信息,请参见documentation

还要注意,您应该 在读取或写入文件时使用requests语句。

with在文件完成后关闭。在这种情况下,您会看到类似

的错误消息
  

ValueError:读取已关闭的文件

答案 1 :(得分:1)

您使用

在第四行打开文件
files = {'photo': open(filename, 'rb')}

第一个request.post调用可能会关闭文件句柄,从而使第二个和第三个request.post无法使用它。

您发布的错误消息包含所需的信息。要解决此问题,只需在每次发布数据之前重新打开文件。

编辑: Wombatz是正确的requests.post读取到文件末尾。

以下是查找文件开头的方法:

files['photo'].seek(0)