Python 如何在电报机器人上发送照片

Python 如何在电报机器人上发送照片,python,telegram-bot,telepot,Python,Telegram Bot,Telepot,我正在实现一个简单的机器人,它应该向我的聊天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 =

我正在实现一个简单的机器人,它应该向我的
聊天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\u id
,但什么也没有发生

我错在哪里


谢谢

您需要通过2个参数

bot.sendPhoto(chat_id, 'URL')
至少需要两个参数;第一张是目标聊天室id,第二张照片有三个选项:

  • 如果照片已经上传到电报服务器,则通过(建议通过,因为您不需要重新上传照片)
  • 如果照片上传到其他地方,通过完整的http url,电报将下载它(最大照片大小为5MB atm)
  • 使用多部分/表单数据发布文件,就像您希望通过浏览器上载文件一样(这种方式的最大照片大小为10MB)

  • 我也尝试过使用请求从python发送消息。也许回答晚了,但把这个留给像我这样的人。。也许它会有用的。。 我成功地执行了
    子流程
    ,如下所示:

    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
    

    如果您有本地映像路径:

    bot.send_photo(chat_id, photo=open('path', 'rb'))
    
    如果您有来自internet的图像url:

    bot.send_photo(chat_id, 'your URl')
    

    在使用发送图像和标题时,我使用了以下命令:

     context.bot.sendPhoto(chat_id=chat_id, photo=
    "url_of_image", caption="This is the test photo caption")
    
    这是在电报中发送照片的完整代码: 只需使用请求库,您就可以做到:

    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'))
    

    你能把准确的呼叫发送到
    sendPhoto()
    ?请修复您发布的代码中的缩进。如果您告诉我们对您的请求的
    电报响应
    ,可能会非常有用。它是bot.sendPhoto而不是bot.send_photo@BiplobDas
    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'))