我的机器人现在已经工作了,但问题是它只能发送文本。我在Bot API中看到有发送照片,视频的功能......但我无法让它工作。有人取得了成功吗?我使用yukuku/telebot
中的python源代码 elif text == '/image':
img = Image.new('RGB', (512, 512))
base = random.randint(0, 16777216)
pixels = [base+i*j for i in range(512) for j in range(512)] # generate sample image
img.putdata(pixels)
output = StringIO.StringIO()
img.save(output, 'JPEG')
reply(img=output.getvalue())
当我更改代码时,没有任何反应。
img = Image.open('image.png')
img.show()
请帮帮我。我需要正确的代码。抱歉我的英语不好。
答案 0 :(得分:4)
我有两个功能,一个适合发送本地图像,另一个适合发送远程图像。
def sendImage():
url = "https://api.telegram.org/bot<Token>/sendPhoto";
files = {'photo': open('/path/to/img.jpg', 'rb')}
data = {'chat_id' : "YOUR_CHAT_ID"}
r= requests.post(url, files=files, data=data)
print(r.status_code, r.reason, r.content)
def sendImageRemoteFile(img_url):
url = "https://api.telegram.org/bot<Token>/sendPhoto";
remote_image = requests.get(img_url)
photo = io.BytesIO(remote_image.content)
photo.name = 'img.png'
files = {'photo': photo}
data = {'chat_id' : "YOUR_CHAT_ID"}
r= requests.post(url, files=files, data=data)
print(r.status_code, r.reason, r.content)
答案 1 :(得分:3)
解决方案是
elif 'Hi' in text:
reply(img=urllib2.urlopen('img url').read())
或
if text == 'help':
reply(img=urllib2.urlopen('img url').read())
答案 2 :(得分:2)
在发送照片之前,您必须执行output.seek(0)
将光标放回文件的开头,否则它将被读为零
答案 3 :(得分:0)
我理解这个问题。这是答案:
def sendImageFromUrl(url):
#this tweak added if request image failed
headers = {'user-agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'}
response = requests.get(url, headers=headers)
#response = requests.get(url)
output = StringIO(response.content)
img = Image.open(output)
img.save(output, 'JPEG')
resp = multipart.post_multipart(BASE_URL + 'sendPhoto', [
('chat_id', str(chat_id)),
('caption', 'Your Caption'),
], [
('photo', 'image.jpg', output.getvalue()),
])
确保您的服务器确实有python模块:requests。
您可以在此处下载:https://pypi.python.org/pypi/requests#downloads
并像你一样投入你的申请
/myapp/app.yaml
/myapp/main.py
/myapp/requests/packages/
/myapp/requests/__init__.py
/myapp/requests/adapters.py
etc...
信用:https://stackoverflow.com/a/17128168/1097372
在第10行之后放入main.py
import requests
from StringIO import StringIO