RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 1394009
Accepted
oleksandrigo
oleksandrigo
Asked:2022-08-27 03:59:01 +0000 UTC2022-08-27 03:59:01 +0000 UTC 2022-08-27 03:59:01 +0000 UTC

如何使用一个 Aiogram 处理程序获取多张照片

  • 772

实际上问题是,有一个特定的处理程序可以捕获照片(压缩),例如,将其发送到某处。

@dp.message_handler(content_types=types.ContentTypes.PHOTO)
async def send_to_admin(message: types.Message):
    await bot.send_photo(chat_id=ADMIN_ID, photo=message.photo[-1].file_id)

因此,如果这个用户(将照片发送给机器人)发送的不是一张,而是两张或更多,他们将像这样分组。

像这样

然后出现了一个奇怪的情况,处理程序对每张照片做出反应,实际上是分开的。事实上,它工作了两次(在照片中的第一个),也就是说,我们message.photo的只有一张照片(尺寸)的变体,但本身没有另一张照片。

因此,回到这个问题,有没有办法用一个处理程序来捕捉这个“组”?毕竟,有办法发送一组照片,但必须有办法将它们作为“组”接收?

python
  • 3 3 个回答
  • 10 Views

3 个回答

  • Voted
  1. Best Answer
    xllwhoami
    2022-08-30T02:26:52Z2022-08-30T02:26:52Z

    看看这个,应该有帮助

    import asyncio
    from typing import List, Union
    
    from aiogram import Bot, Dispatcher, executor, types
    from aiogram.dispatcher.handler import CancelHandler
    from aiogram.dispatcher.middlewares import BaseMiddleware
    
    bot = Bot(token="TOKEN_HERE")  # Place your token here
    dp = Dispatcher(bot)
    
    
    class AlbumMiddleware(BaseMiddleware):
        """This middleware is for capturing media groups."""
    
        album_data: dict = {}
    
        def __init__(self, latency: Union[int, float] = 0.01):
            """
            You can provide custom latency to make sure
            albums are handled properly in highload.
            """
            self.latency = latency
            super().__init__()
    
        async def on_process_message(self, message: types.Message, data: dict):
            if not message.media_group_id:
                return
    
            try:
                self.album_data[message.media_group_id].append(message)
                raise CancelHandler()  # Tell aiogram to cancel handler for this group element
            except KeyError:
                self.album_data[message.media_group_id] = [message]
                await asyncio.sleep(self.latency)
    
                message.conf["is_last"] = True
                data["album"] = self.album_data[message.media_group_id]
    
        async def on_post_process_message(self, message: types.Message, result: dict, data: dict):
            """Clean up after handling our album."""
            if message.media_group_id and message.conf.get("is_last"):
                del self.album_data[message.media_group_id]
    
    
    @dp.message_handler(content_types=types.ContentType.ANY)
    async def handle_albums(message: types.Message, album: List[types.Message]):
        """This handler will receive a complete album of any type."""
        media_group = types.MediaGroup()
        for obj in album:
            if obj.photo:
                file_id = obj.photo[-1].file_id
            else:
                file_id = obj[obj.content_type].file_id
    
            try:
                # We can also add a caption to each file by specifying `"caption": "text"`
                media_group.attach({"media": file_id, "type": obj.content_type})
            except ValueError:
                return await message.answer("This type of album is not supported by aiogram.")
    
        await message.answer_media_group(media_group)
    
    
    if __name__ == "__main__":
        dp.middleware.setup(AlbumMiddleware())
        executor.start_polling(dp, skip_updates=True)
    
    • 1
  2. Дмитрий
    2022-08-29T03:52:15Z2022-08-29T03:52:15Z

    这是另一种选择。

    这样我们就可以将接收到的照片保存在数据库中。下载方法无关紧要,即使是专辑,甚至一次一张。好吧,可以同时与多个用户一起工作,不使用异步是一种罪过。

    from aiogram import types, Dispatcher
    from create_bot import dp,bot
    from aiogram.dispatcher import FSMContext
    from aiogram.dispatcher.filters.state import State, StatesGroup
    from Keyboards import client_kb
    from Data_base import sqlite_db
    from aiogram.types import ReplyKeyboardMarkup, KeyboardButton
    
    
    List_photo = {}
    
    
    class FSMReport(StatesGroup):
        city = State()
        address = State()
        photo = State()
    
           
    async def report_photo(message: types.Message, state=FSMContext):
        global List_photo
        key = str(message.from_user.id)
        List_photo.setdefault(key, [])
        if message.content_type == 'photo':
            List_photo[key].append(message.photo[0].file_id)            
        elif message.content_type == 'text':
            async with state.proxy() as data:
                data['photo'] = ','.join(List_photo[key])
                List_photo.pop(key)
            await sqlite_db.sql_add_photo_report(state)
            await bot.send_message(message.from_user.id, 'Готово', reply_markup=client_kb.kb_client)
            await state.finish()
    
    
    def register_handlers_client(dp: Dispatcher):        
        dp.register_message_handler(report_photo, content_types=['photo', 'text'], state=FSMReport.photo)
    

    结果:

    在此处输入图像描述

    我们通过 key data['photo'] 在列表中看到,id 的数量等于照片的数量。他们没有一次加载一个。

    • 0
  3. Азат
    2022-09-01T23:39:30Z2022-09-01T23:39:30Z
    TOKEN = "1234646854fdghdfhfghfghssfhhgh"
    
    def send_group_img(chat_id, text):
        temp_files_list = list()
        media = list()
        files = dict()
        for filename in os.listdir("temp"):
            temp_files_list.append(f'{os.getcwd()}\\temp\\{filename}')
        for f in enumerate(temp_files_list):
            files[f"random-name-{f[0]}"] = open(f[1], "rb")
            if f[0] == 0:
                media.append({"type": "photo",
                              "media": f"attach://random-name-{f[0]}",
                              "caption": text}
                             )
            else:
                media.append({"type": "photo",
                              "media": f"attach://random-name-{f[0]}"})
        params = {
            "chat_id": chat_id, "media": str(media).replace("'", '"')}
        request_url = "https://api.telegram.org/bot" + TOKEN + "/sendMediaGroup"
        result = requests.post(request_url, params=params, files=files)
        if result.status_code == 200:
            return True
        else:
            return False
    
    • -1

相关问题

  • 是否可以以某种方式自定义 QTabWidget?

  • telebot.anihelper.ApiException 错误

  • Python。检查一个数字是否是 3 的幂。输出 无

  • 解析多个响应

  • 交换两个数组的元素,以便它们的新内容也反转

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5