[Python] How can I implement uploading multiple files at once in aiogram?

Discussão em 'Python' iniciado por Stack, Abril 1, 2025.

  1. Stack

    Stack Membro Participativo

    I need to implement multiple file uploads in one message. I couldn't find how to do it in the official documentation.

    For example, I implemented only loading one file at a time and storing them in a separate directory.

    Now the code works in such a way that it saves files in a directory and writes the file number, so I understand how many are saved.

    import os
    import asyncio
    import logging

    from aiogram.types import Message
    from aiogram import Bot, Dispatcher, types, Router, F
    from aiogram.types import BotCommand, BotCommandScopeDefault
    from aiogram.filters.command import Command

    router: Router = Router()

    logging.basicConfig(level=logging.INFO)
    bot = Bot(token="")
    dp = Dispatcher()

    EXTENSION = '<>'
    FILE = ''
    counter_files = 0

    UPLOAD_FOLDER = "uploads/"
    os.makedirs(UPLOAD_FOLDER, exist_ok=True)

    @dp.message(Command("start"))
    async def cmd_start(message: types.Message):
    await message.answer("Hello!")


    @dp.message(Command("check_status"))
    async def cmd_start(message: types.Message):
    await message.answer("File: " + FILE)

    @dp.message(Command("message"))
    async def cmd_start(message: types.Message):
    await message.answer("Message: " + message.text)


    @dp.message(F.document)
    async def get_doc(message: types.Message, bot: Bot):
    global FILE, counter_files
    file = await bot.get_file(message.document.file_id)
    file_path = file.file_path

    if file_path.endswith(EXTENSION):
    destination = os.path.join(UPLOAD_FOLDER, f'file_{counter_files}.{EXTENSION}')
    await bot.download_file(file_path, destination)

    FILE = destination
    counter_files += 1
    await message.answer(f"Your {FILE} is success downloaded!")
    else:
    await message.answer(f"Format is wrong! Download {EXTENSION}")


    async def set_commands():
    commands = [BotCommand(command='start', description='start chating'),
    BotCommand(command='check_status', description='check status'),
    BotCommand(command='message', description='your message'),]

    await bot.set_my_commands(commands, BotCommandScopeDefault())


    async def main():
    await set_commands()
    await dp.start_polling(bot)

    if __name__ == "__main__":
    asyncio.run(main())

    Continue reading...

Compartilhe esta Página