[英]How to send photo on telegram bot
我只是在實現一個簡單的機器人,它應該向我的chat_id
發送一些照片和視頻。 好吧,我正在使用python,這是腳本
import sys
import time
import random
import datetime
import telepot
def handle(msg):
chat_id = msg['chat']['id']
command = msg['text']
print 'Got command: %s' % command
if command == 'command1':
bot.sendMessage(chat_id, *******)
elif command == 'command2':
bot.sendMessage(chat_id, ******)
elif command == 'photo':
bot.sendPhoto(...)
bot = telepot.Bot('*** INSERT TOKEN ***')
bot.message_loop(handle)
print 'I am listening ...'
while 1:
time.sleep(10)
在bot.sendphoto
行中,我將插入圖像的路徑和chat_id
,但沒有任何反應。
我哪里錯了?
謝謝
如果您有本地圖像路徑:
bot.send_photo(chat_id, photo=open('path', 'rb'))
如果您有來自互聯網的圖片網址:
bot.send_photo(chat_id, 'your URl')
只需使用Requests lib,您就可以做到:
def send_photo(chat_id, file_opened):
method = "sendPhoto"
params = {'chat_id': chat_id}
files = {'photo': file_opened}
resp = requests.post(api_url + method, params, files=files)
return resp
send_photo(chat_id, open(file_path, 'rb'))
我也嘗試過使用請求從 python 發送。 也許這是遲到的答案,但是把這個留給像我這樣的其他人..也許它會派上用場..我成功地使用了這樣的subprocess
:
def send_image(botToken, imageFile, chat_id):
command = 'curl -s -X POST https://api.telegram.org/bot' + botToken + '/sendPhoto -F chat_id=' + chat_id + " -F photo=@" + imageFile
subprocess.call(command.split(' '))
return
我在使用python-telegram-bot發送圖像和標題時使用了以下命令:
context.bot.sendPhoto(chat_id=chat_id, photo=
"url_of_image", caption="This is the test photo caption")
import telepot bot = telepot.Bot('______ YOUR TOKEN ________') # here replace chat_id and test.jpg with real things bot.sendPhoto(chat_id, photo=open('test.jpg', 'rb'))
您需要傳遞 2 個參數
bot.sendPhoto(chat_id, 'URL')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.