Im writing a telegram bot using the python telepot api. I’m now stuck at the point where I want to send a picture which directly comes from an URL without storing it locally. Telepot provides the following instruction to send a photo:
>>> f = open('zzzzzzzz.jpg', 'rb') # some file on local disk
>>> response = bot.sendPhoto(chat_id, f)
Now im using
f = urllib2.urlopen('http://i.imgur.com/B1fzGoh.jpg')
bot.sendPhoto(chat_id, f)
The problem here is that urllib2.urlopen('url')
provide me file-like object like:
<addinfourl at 140379102313792 whose fp = <socket._fileobject object at 0x7fac8e86d750>>
and not like open('myFile.jpg', 'rb')
a file object like:
<open file 'app-root/runtime/repo/myImage.jpg', mode 'rb' at 0x7fac8f322540>
If I send the file-like object in sendPhoto() I get the following error:
Traceback (most recent call last):
[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')
There is a solution for a different telegram-bot project provided here where they send the urllib2.urlopen('url').read()
back to telegram but in my case this generates the same error as without .read() .
How could I get the file from the url as file object (best would be without saving it locally)?
Or how do I get the “file object” out of the “file-like object” provided by urlopen()?
Thanks for any help 🙂
2
Answers
Yes.
You can make it async (or not):
In current Bot Api 2.3.1, You can simply send url of file to the server:
That’s it.
You don’t even need to download it, Telegram would upload it by itself.