-1

I figure out how to pick a specific picture in a directory.

bot.send_photo(chat_id=chat_id, photo=open('/Users/Iamawesome/Desktop/test/599d6f972525a.jpg', 'rb'))

But how can I pick a random picture? Thank you.

UPDATE I figure out a little bit, but i still don't handle any messages or errors

  @BOT.message_handler(commands=['photo'])
  def send_rand_photo(message):
     photo = random.choice([
                                x for x in os.listdir(PATH)
                                if os.path.isfile(os.path.join(PATH, x))
                                ])
with open (photo, "rb") as file:
    BOT.send_photo(message.chat.id, file)
Alex Nikitin
  • 841
  • 1
  • 10
  • 29
  • unless you can make an array of all the contents in that directory and then split out which ones are pictures you can't. There would be no way of knowing what is in that directory and therefor random doesn't work. – Cayce K Feb 21 '18 at 14:12
  • If the file ends with `jpg` then it's most likely an image –  Feb 21 '18 at 14:15

4 Answers4

1

Assuming the directory only contains images you could use os.listdir and random.choice.

import random
import os
directory = "/Users/Iamawesome/Desktop/test/"
random_image = random.choice(os.listdir(directory))
print directory + random_image
Karl Graham
  • 151
  • 4
1

instead of trying this with api you can use os and random module to pick the picture.try this

     path = r"/home/mark/bot/images"
random_filename = random.choice([
                                    x for x in os.listdir(path)
                                    if os.path.isfile(os.path.join(path, x))
                                    ])
bot.sendPhoto(photo, random_filename)
om tripathi
  • 300
  • 1
  • 5
  • 20
  • Using this method i am handling an error - A request to the Telegram API was unsuccessful. The server returned HTTP 400 Bad Request. Response body: [b'{"ok":false,"error_code":400,"description":"Bad Request: failed to get HTTP URL content"}'] But servers work, i checked it – Alex Nikitin Feb 21 '18 at 15:08
0

Here is solution

@bot.message_handler(content_types=['text'])
def send_rand_photo(message):
if message.text =='фото':

    all_photo_in_directory=os.listdir(PATH)
    random_photo=random.choice (all_photo_in_directory)
    img=open (PATH + '/' +random_photo, 'rb')
    bot.send_chat_action(message.from_user.id,'upload_photo')
    bot.send_photo(message.from_user.id,img)
    img.close()
Alex Nikitin
  • 841
  • 1
  • 10
  • 29
0

This is correct function.

import random
import os

def init(update,context):
    directory = "/path"
    random_image = random.choice(os.listdir(directory))
    bot.send_photo(update.message.chat_id, photo=open(directory + random_image,'rb'))