繁体   English   中英

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

[英]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')

sendPhoto至少需要两个参数; 第一个是目标chat_id ,对于第二张照片,您有三个选项:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM