2015-07-03 548 views
6

我做了一個電報機器人,根據請求使用pyTelegramBotAPI包裝發送照片。所以我試圖放置一個虛擬的照片URL並測試機器人是否可以發送圖像,但是由於以下錯誤而失敗。從Telegram Bot發送URL的照片

telebot.apihelper.ApiException: sendPhoto failed. Returned result: <Response [400]>

我不知道是什麼錯誤,但我怎麼能發送正確使用電報博特API從URL中的照片?這裏是我的代碼

import telebot 
import time 
import urllib 
from io import BytesIO 
from PIL import Image 

TOKEN = '<token here>' 
url='http://scontent-b.cdninstagram.com/hphotos-xfa1/t51.2885-15/e15/10919672_584633251672188_179950734_n.jpg' 

def listener(*messages): 
    for m in messages: 
     chatid = m.chat.id 
     if m.content_type == 'text': 
      text = m.text 
      name = m.fromUser.first_name 
      msgid = m.message_id 
      if(text.startswith('/photo')): 
       img = BytesIO(urllib.request.urlopen(url).read()) 
       tb.send_chat_action(chatid, 'upload_photo') 
       tb.send_photo(chatid, img, reply_to_message_id=msgid) 


tb = telebot.TeleBot(TOKEN) 
tb.get_update() # cache exist message 
tb.set_update_listener(listener) #register listener 
tb.polling() 
while True: 
    time.sleep(1) 

我不知道我是否錯過了某些東西。

回答

6

試試這個:

import telebot 
import time 
import urllib 

url = 'http://scontent-b.cdninstagram.com/hphotos-xfa1/t51.2885-15/e15/10919672_584633251672188_179950734_n.jpg' 
f = open('out.jpg','wb') 
f.write(urllib.request.urlopen(url).read()) 
f.close() 

def listener(*messages): 
    for m in messages: 
     chat_id = m.chat.id 
     if m.content_type == 'text': 
      text = m.text 
      msgid = m.message_id 
      if text.startswith('/photo'): 
       tb.send_chat_action(chat_id, 'upload_photo') 
       img = open('out.jpg', 'rb') 
       tb.send_photo(chat_id, img, reply_to_message_id=msgid) 
       img.close() 


tb = telebot.TeleBot(TOKEN) 
tb.set_update_listener(listener) #register listener 
tb.polling() 

while True: 
    time.sleep(0) 

或(使用pyTelegramBotAPI 0.2.0)

import telebot 
import time 
import urllib 

url='http://scontent-b.cdninstagram.com/hphotos-xfa1/t51.2885-15/e15/10919672_584633251672188_179950734_n.jpg' 
f = open('out.jpg','wb') 
f.write(urllib.request.urlopen(url).read()) 
f.close() 

tb = telebot.TeleBot(TOKEN) 

@tb.message_handler(commands=['photo']) 
def send_photo(message): 
    tb.send_chat_action(message.chat.id, 'upload_photo') 
    img = open('out.jpg', 'rb') 
    tb.send_photo(message.chat.id, img, reply_to_message_id=message.message_id) 
    img.close() 

tb.polling() 

while True: 
    time.sleep(0) 
+0

所以我們需要下載整個文件到本地文件夾上傳到電報畢竟之前。有什麼辦法可以在下載的時候縮小圖像大小,因爲我在機器上完全運行腳本? – Zerocchi

+0

我不知道你到底想做什麼,但我確定有辦法用python壓縮圖像,只有不會_while_下載。並且確保在不再需要該文件時從計算機中刪除該圖像。 – Pete

+0

我的代碼在這裏 - 我相信,因爲我是python新手 - 不需要將圖像下載到本地文件夾中:http://stackoverflow.com/a/32441772/1097372 – Iyas

2
elif 'Hi' in text: 
    reply(img=urllib2.urlopen('img url').read())