我正在使用 python telepot api编写一个电报机器人。我现在被困在我想发送直接来自 URL 的图片而不将其存储在本地的地步。Telepot提供以下指令来发送照片:
>>> f = open('zzzzzzzz.jpg', 'rb') # some file on local disk
>>> response = bot.sendPhoto(chat_id, f)
现在我正在使用
f = urllib2.urlopen('http://i.imgur.com/B1fzGoh.jpg')
bot.sendPhoto(chat_id, f)
这里的问题是urllib2.urlopen('url')
为我提供了类似文件的对象,例如:
<addinfourl at 140379102313792 whose fp = <socket._fileobject object at 0x7fac8e86d750>>
而不是像这样open('myFile.jpg', 'rb')
的文件对象:
<open file 'app-root/runtime/repo/myImage.jpg', mode 'rb' at 0x7fac8f322540>
如果我在 sendPhoto() 中发送类似文件的对象,则会收到以下错误: Traceback(最近一次调用最后一次):
[Wed Feb 10 06:21:09 2016] [error] File "/var/lib/openshift/56b8e2787628e1484a00013e/python/virtenv/lib/python2.7/site-packages/telepot/__init__.py", line 340, in handle
[Wed Feb 10 06:21:09 2016] [error] callback(update['message'])
[Wed Feb 10 06:21:09 2016] [error] File "/var/lib/openshift/56b8e2787628e1484a00013e/app-root/runtime/repo/moviequiz_main.py", line 35, in handle
[Wed Feb 10 06:21:09 2016] [error] response = bot.sendPhoto(chat_id, gif)
[Wed Feb 10 06:21:09 2016] [error] File "/var/lib/openshift/56b8e2787628e1484a00013e/python/virtenv/lib/python2.7/site-packages/telepot/__init__.py", line 230, in sendPhoto
[Wed Feb 10 06:21:09 2016] [error] return self._sendFile(photo, 'photo', p)
[Wed Feb 10 06:21:09 2016] [error] File "/var/lib/openshift/56b8e2787628e1484a00013e/python/virtenv/lib/python2.7/site-packages/telepot/__init__.py", line 226, in _sendFile
[Wed Feb 10 06:21:09 2016] [error] return self._parse(r)
[Wed Feb 10 06:21:09 2016] [error] File "/var/lib/openshift/56b8e2787628e1484a00013e/python/virtenv/lib/python2.7/site-packages/telepot/__init__.py", line 172, in _parse
[Wed Feb 10 06:21:09 2016] [error] raise BadHTTPResponse(response.status_code, response.text)
[Wed Feb 10 06:21:09 2016] [error] BadHTTPResponse: (414, u'<html>\\r\\n<head><title>414 Request-URI Too Large</title></head>\\r\\n<body bgcolor="white">\\r\\n<center><h1>414 Request-URI Too Large</h1></center>\\r\\n<hr><center>nginx/1.9.1</center>\\r\\n</body>\\r\\n</html>\\r\\n')
这里提供了一个针对不同电报机器人项目的解决方案,他们将其发送urllib2.urlopen('url').read()
回电报,但在我的情况下,这会产生与没有 .read() 相同的错误。
如何从 url 获取文件作为文件对象(最好不要在本地保存)?或者如何从 urlopen() 提供的“类文件对象”中获取“文件对象”?
谢谢你的帮助 :)