首页 > 解决方案 > 在我点击 bot telethon 电报中的按钮后发送 x 照片

问题描述

@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)

我需要从目录中发送 n(在电报的输入中)随机照片,但它说

ValueError:无法将 bonni media-jpg 转换为媒体。不是现有文件、HTTP URL 或有效的类似 bot API 的文件 ID

标签: telegramtelethon

解决方案


正如错误所述:

ValueError:无法将bonni media-jpg转换为媒体。不是现有文件、HTTP URL 或有效的类似 bot API 的文件 ID

在循环保护里面,你正在做os.path.join(path, x). 但是,您的x不包含完整路径。然后在工作目录中搜索该文件,但没有找到。您还需要在那里指定正确的路径:

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))
])

推荐阅读