I’m trying to create a function that randomly selects 10 photos locally. After that, it sends this data array to the user in Telegram.
Here is a piece of my code.
def send_certificates(message):
text = 'tex'
# The path to the folder with photos
path = 'D://PYTHON//PROGRAMM//TelegramBot//img//certificates'
# Получаем список всех файлов в папке
file_list = os.listdir(path)
# We filter the list, leaving only files with the extension.jpg or .png (or other supported formats)
photo_list = [file for file in file_list if file.endswith('.jpg') or file.endswith('.png')]
# If there are less than 10 photos in the folder, we display a message about it
if len(photo_list) < 10:
print("There are not enough photos in the folder!")
else:
# Randomly select 10 photos from the list
selected_photos = random.sample(photo_list, 10)
medias = []
# We print the names of the selected photos
for num, png in enumerate(selected_photos):
if num == 0:
medias.append(InputMediaPhoto(media=png), caption=text)
else:
medias.append(InputMediaPhoto(media=png))
bot.send_media_group(chat_id=message.chat.id, media=medias)
But I get this error
Traceback (most recent call last):
File "D:PYTHONPROGRAMMTelegramBotmain.py", line 305, in <module>
bot.polling(none_stop=True)
File "D:PYTHONPROGRAMMTelegramBotvenvlibsite-packagestelebot__init__.py", line 1043, in polling
self.__threaded_polling(non_stop=non_stop, interval=interval, timeout=timeout, long_polling_timeout=long_polling_timeout,
File "D:PYTHONPROGRAMMTelegramBotvenvlibsite-packagestelebot__init__.py", line 1118, in __threaded_polling
raise e
File "D:PYTHONPROGRAMMTelegramBotvenvlibsite-packagestelebot__init__.py", line 1074, in __threaded_polling
self.worker_pool.raise_exceptions()
File "D:PYTHONPROGRAMMTelegramBotvenvlibsite-packagestelebotutil.py", line 147, in raise_exceptions
raise self.exception_info
File "D:PYTHONPROGRAMMTelegramBotvenvlibsite-packagestelebotutil.py", line 90, in run
task(*args, **kwargs)
File "D:PYTHONPROGRAMMTelegramBotvenvlibsite-packagestelebot__init__.py", line 6788, in _run_middlewares_and_handler
result = handler['function'](message)
File "D:PYTHONPROGRAMMTelegramBotmain.py", line 299, in info
send_certificates(message)
File "D:PYTHONPROGRAMMTelegramBotmain.py", line 205, in send_certificates
medias.append(InputMediaPhoto(media=png), caption=text)
TypeError: list.append() takes no keyword arguments
2
Answers
You’re doing
you probably meant to do
In the first part of your if/else statement:
you call
medias.append()
with the main argumentInputMediaPhoto(media=png)
and the keyword argumentcaption=text
. While you didn’t post the__init__()
method forInputMediaPhoto
, is it possible you meant to writeInputMediaPhoto(media=png, caption=text)
? This would pass themedia
andcaption
parameters to theInputMediaPhoto
constructor, so your syntax should be: