Answer the question
In order to leave comments, you need to log in
How to output a random image from a file?
We need the code to send a random photo from the directory.
Used two methods, settled on the error "Syntax error in file name, folder name or volume label: ..."
DIR = 'D:\Python\telegramtest\photos'
photo = open(os.path.join(DIR, random. choice(os.listdir(DIR))))
bot.send_photo(message.chat.id, photo)
path = r'D:\Python\telegramtest\photos'
photo = random.choice([
x for x in os.listdir (path)
if os.path.isfile(os.path.join(path, x))
])
bot.send_photo(message.chat.id, photo)
Answer the question
In order to leave comments, you need to log in
No need to take on bots without knowing the basics of Python!
And on business, at first without bot receive the list of images from a folder. Next, get a random element from the resulting list. Well, then you can connect the bot.
In python (as in many other programming languages), the \ character in string values is used for escaping and for special characters. For example, \t is a tab, \n is a line feed. Therefore, using \ in strings is not so easy. You must either prefix the string with an r to disable this behavior (r'c:\telegram'), or escape the slashes: ('c:\\telegram').
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question