【问题标题】:How to send photo on telegram bot如何在电报机器人上发送照片
【发布时间】:2016-08-15 04:04:05
【问题描述】:

我只是在实现一个简单的机器人,它应该将一些照片和视频发送到我的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,但没有任何反应。

我哪里错了?

谢谢

【问题讨论】:

  • 你能把确切的电话发给sendPhoto()吗?请修复您发布的代码中的缩进。
  • 如果您将telegram response 告诉您的请求可能会很有帮助

标签: python telegram-bot telepot


【解决方案1】:

如果你有本地图片路径:

bot.send_photo(chat_id, photo=open('path', 'rb'))

如果您有来自互联网的图片网址:

bot.send_photo(chat_id, 'your URl')

【讨论】:

【解决方案2】:

只需使用 Requests 库即可:

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

【讨论】:

  • api_url有错误
  • api_url 不是 var,是必须放的字符串
【解决方案3】:

我在使用python-telegram-bot 发送图片和标题时使用了以下命令:

 context.bot.sendPhoto(chat_id=chat_id, photo=
"url_of_image", caption="This is the test photo caption")

【讨论】:

    【解决方案4】:

    我也尝试过使用请求从 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
    

    【讨论】:

      【解决方案5】:

      这是在电报中发送照片的完整代码:

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

      【讨论】:

        【解决方案6】:

        你需要传递 2 个参数

        bot.sendPhoto(chat_id, 'URL')
        

        【讨论】:

          【解决方案7】:

          sendPhoto至少需要两个参数;第一个是目标chat_id,第二个是photo,你有三个选项:

          1. 如果照片已经上传到电报服务器,请传递file_id(推荐,因为您不需要重新上传)。
          2. 如果照片上传到其他地方,请传递完整的 http url,然后电报将下载它(最大照片大小为 5MB atm)。
          3. 使用 multipart/form-data 发布文件,就像您想通过浏览器上传文件一样(这种方式最大照片大小为 10MB)。

          【讨论】:

            猜你喜欢
            • 2016-10-17
            • 1970-01-01
            • 2019-05-14
            • 2021-04-20
            • 2021-02-10
            • 2016-07-18
            • 1970-01-01
            • 1970-01-01
            • 2019-03-28
            相关资源
            最近更新 更多