我正在使用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()中发送类文件对象,我会收到以下错误: 回溯(最近一次调用最后一次):
[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()相同的错误。
我如何从文件对象中获取文件(最好不在本地保存)? 或者我如何获得&#34;文件对象&#34;超出&#34;文件类对象&#34;由urlopen()提供?
感谢您的帮助:)
答案 0 :(得分:2)
是
您可以将其设为异步(或不):
async with aiohttp.get("http://i.imgur.com/B1fzGoh.jpg") as r:
result = r.read()
await self.sendPhoto(chat_id, ('image.jpg', result))
答案 1 :(得分:1)
在当前的Bot Api 2.3.1中,您只需将文件的URL发送到服务器:
QT += core
QT -= gui
CONFIG += c++11
TARGET = test
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
QT += network
SOURCES += main.cpp \
test_interface.cpp \
motomanlibrary.cpp \
processing.cpp
SOURCES += main.cpp \
test_interface.h \
motomanlibrary.h \
processing.h
那就是它。
您甚至不需要下载它,Telegram会自行上传。