Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Telegram Bot - Send Image

I'd like to send a Image (via URL or Path), on request. I use the source code here. The code has already a sample to send an image (via URL or Path), but I don't get it since I'm new to Python.

Here's the sample code snippet:

elif text == '/image':        #request
    img = Image.new('RGB', (512, 512))
    base = random.randint(0, 16777216)
    pixels = [base+i*j for i in range(512) for j in range(512)]  # generate sample image
    img.putdata(pixels)
    output = StringIO.StringIO()
    img.save(output, 'JPEG')
    reply(img=output.getvalue())

Some API infos can be found here.

Thanks for your patience.

like image 877
ColinDave Avatar asked Sep 01 '15 08:09

ColinDave


People also ask

How to create a telegram bot?

First, we will need a Telegram account, if you don't have one you can create one easily. In telegram, search for BotFather. It will look as shown in the image. Then we have to send start and then follow the instructions given by BotFather. In short, /start > /newbot > name for bot > username for Bot (unique).

How can I get the file ID of a Telegram photo?

Once the photo is sent for the first time, you can obtain the Telegram's file id of it from the response. Passing Telegram's file id instead instead of the file object is faster, because you just point Telegram to a file it already has and not reading and sending the same file over and over again.

How to analyze the images sent to the bot?

In order to analyze the images send to the bot, first we need to install and build Darknet. All the installation commands are available on the install.sh file in the Glitch project.

How to reply to a bot that doesn't reply?

Try sending /start or /greet to the bot, it should reply "Hello, how are you?" But if we don't want to reply to message then we can use send_message method. To use send_message, we will require the id of the sender.


2 Answers

To send a photo from URL:

bot.send_photo(chat_id=chat_id, photo='https://telegram.org/img/t_logo.png')

To send a photo from local Drive:

bot.send_photo(chat_id=chat_id, photo=open('tests/test.png', 'rb'))

Here is the reference documentation.

like image 150
Saravanan Manoharan Avatar answered Sep 22 '22 06:09

Saravanan Manoharan


I was struggling to connect the python-telegram-bot examples with the above advice. Especially, while having context and update, I couldnt find chatid and bot. Now, my two cents:

pic=os.path.expanduser("~/a.png")
context.bot.send_photo(chat_id=update.effective_chat.id, photo=open(pic,'rb'))
like image 39
jaromrax Avatar answered Sep 22 '22 06:09

jaromrax