Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send photo on telegram bot

i'm just implementing a simple bot who should send some photos and videos to my chat_id. Well, i'm using python, this is the script

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)

In the line bot.sendphoto I would insert the path and the chat_id of my image but nothing happens.

Where am I wrong?

thanks

like image 272
rollotommasi Avatar asked Apr 21 '16 19:04

rollotommasi


People also ask

How do I send a picture using Telebot?

Method: Telebot::Client#send_photo Photo to send. You can either pass a file_id as String to resend a photo that is already on the Telegram servers, or upload a new photo using multipart/form-data.

How can I get image from Telegram bot?

From telegram's docs: On success, a File object is returned. The file can then be downloaded via the link https://api.telegram.org/file/bot/, where is taken from the response. It is guaranteed that the link will be valid for at least 1 hour.

Can I send message by bot in Telegram?

Getting StartedOpen the telegram app and search for @BotFather. Click on the start button or send “/start”. Then send “/newbot” message to set up a name and a username. After setting name and username BotFather will give you an API token which is your bot token.


3 Answers

If you have local image path:

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

If you have url of image from internet:

bot.send_photo(chat_id, 'your URl')
like image 192
Majid A Avatar answered Sep 20 '22 21:09

Majid A


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'))
like image 25
jarh1992 Avatar answered Sep 19 '22 21:09

jarh1992


I've tried also sending from python using requests. Maybe it's late answer, but leaving this here for others like me.. maybe it'll come to use.. I succeded with subprocess like so:

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
like image 43
Cipri Avatar answered Sep 20 '22 21:09

Cipri