首页 > 解决方案 > 上传一批文件后如何通知

问题描述

我有这样的代码

async def handle_docs_photo(message: types.Message):
    try:
        files = await bot.get_file(message.photo[-1].file_id)
        # await message.answer('data/' + str(message.from_user.id) + files.file_path[-12:])
        await bot.download_file_by_id(message.photo[-1].file_id,
                                      'data/' + str(message.from_user.id) + '/' + files.file_path[-12:])
        logger.info('{} {}', message.from_user.username,
                    'data/' + str(message.from_user.first_name) + '/' + files.file_path[-12:])
        await message.answer('Все сохранено', reply_markup=inkb)
    except Exception as e:
        await message.answer(f'{message.text}, {e}')

处理后,它发出一条消息

await message.answer('Все сохранено', reply_markup=inkb)

并显示内联键盘。为了防止每次发送一批文件时弹出消息,有一个想法是我需要将文件收集到一个列表中并循环处理它们。

问题是在哪里做这个?

标签: pythonpython-3.xtelegram-botaiogram

解决方案


因为handle_docs_photo()每张照片都会触发多次。我使用这个小技巧global variabletime of trigger控制下一个触发器的逻辑。

global before
before = datetime.datetime.now()

@bot.message_handler... #your proper decorator that you didn't mention
async def handle_docs_photo(message): #your function
    global before
    now = datetime.datetime.now()

    # stuff that need to be done always.
    print(message)

    #you can adjust the timedelta to your needs
    if now - before > datetime.timedelta(seconds=5):
        # stuff that need to be done based on the consecutive triggers.
        # it executes for the first time and
        # if the time difference is >5s perform below logic.
        await message.answer('Все сохранено', reply_markup=inkb) #your msg
    before = now

推荐阅读