sending x photos after i click a button in a bot telethon telegram

Viewed 186
@bot.on(events.CallbackQuery)
async def handler(event):
global fotomandate
global i
if event.data == b"1":
    await event.respond("how many photos do i send?") 
    numerofoto = int(input("how many photos do i send?")) ##ignore this line i'll fix later
    print (numerofoto)
    while i < numerofoto:
        path = (r"C:\Users\x\Desktop\Nuova cartella (2)")
        fotorandom = random.choice([
            x for x in os.listdir(r"C:\Users\x\Desktop\Nuova cartella (2)")
            if os.path.isfile(os.path.join(path, x))
        ])
        i += 1
        await event.reply(file=fotorandom)

i need to send n(in input on telegram) random photos from a directory but it says

ValueError: Failed to convert bonni media-jpg to media. Not an existing file, an HTTP URL or a valid bot-API-like file ID

1 Answers

As the error states:

ValueError: Failed to convert bonni media-jpg to media. Not an existing file, an HTTP URL or a valid bot-API-like file ID

Inside the loop guard, you're doing os.path.join(path, x). However, your x does not contain the full path. Then the file is searched in the working directory, but it is not found. You need to specify the correct path there too:

fotorandom = random.choice([
    os.path.join(path, x)  # <- new
    for x in os.listdir(path)  # <- better to avoid repeating dir
    if os.path.isfile(os.path.join(path, x))
])
Related