我正在使用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')对于different telegram-bot project provided here,有一种解决方案,可以将urllib2.urlopen('url').read()发送回电报,但在我的示例中,这会生成与没有.read()时相同的错误。
如何从url中获取文件作为文件对象(最好不将其保存在本地)?或者如何从urlopen()提供的“类文件对象”中获取“文件对象”?
感谢您的帮助:)
发布于 2017-05-03 22:49:24
在当前的Bot Api 2.3.1中,您可以简单地将文件的url发送到服务器:
bot.sendPhoto(chat_id, "http://i.imgur.com/B1fzGoh.jpg");就这样。
你甚至不需要下载,Telegram会自动上传。
发布于 2016-04-24 23:52:55
是。
您可以将其设置为异步(或不同步):
async with aiohttp.get("http://i.imgur.com/B1fzGoh.jpg") as r:
result = r.read()
await self.sendPhoto(chat_id, ('image.jpg', result))https://stackoverflow.com/questions/35314526
复制相似问题