[英]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.