簡體   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