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

rol*_*asi 7 python telegram-bot telepot

我只是实现了一个简单的机器人,该机器人应该将一些照片和视频发送给我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)
Run Code Online (Sandbox Code Playgroud)

在这一行中,bot.sendphoto我将插入chat_id图像的路径和,但是什么也没有发生。

我哪里错了?

谢谢

Maj*_*d A 19

如果您有本地图像路径:

bot.send_photo(chat_id, photo=open('path', 'rb'))
Run Code Online (Sandbox Code Playgroud)

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

bot.send_photo(chat_id, 'your URl')
Run Code Online (Sandbox Code Playgroud)


Bip*_*Das 7

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

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'))
Run Code Online (Sandbox Code Playgroud)


小智 6

我也尝试过使用请求从 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
Run Code Online (Sandbox Code Playgroud)


小智 6

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

 context.bot.sendPhoto(chat_id=chat_id, photo=
"url_of_image", caption="This is the test photo caption")
Run Code Online (Sandbox Code Playgroud)


jar*_*992 5

Just using the Requests lib you can do it:

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'))
Run Code Online (Sandbox Code Playgroud)


小智 2

你需要传递2个参数

bot.sendPhoto(chat_id, 'URL')
Run Code Online (Sandbox Code Playgroud)