You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在aiogram中间件中添加位置参数?解决request缺失报错

问题分析与解决

错误根源

报错TypeError: on_start() missing 1 required positional argument: 'request'的核心原因是:你没有注册负责注入request对象的DbSession中间件,同时代码里还存在几处冗余和冲突问题,导致依赖无法正常传递。

具体修复步骤

1. 注册DbSession中间件

必须在Dispatcher中注册DbSession中间件,否则request对象不会被注入到处理函数的参数里。

2. 移除重复的Handler注册

你在register_fsm函数和start()函数里重复注册了on_start,这会导致重复绑定,保留一处即可。

3. 解决States类重复定义问题

代码里同时从main导入States又自己定义了同名类,会造成冲突,删掉其中一个重复定义。

4. 补全DbSession的依赖导入

db_middleware.py里需要导入Request类,否则无法实例化request对象。

修改后的完整代码示例

修改后的fsm.py

import asyncio
import logging

from aiogram import Bot, types, Dispatcher
from aiogram.filters import Command, Text
from aiogram.fsm.context import FSMContext
from aiogram.fsm.state import StatesGroup, State
from aiogram.types import BotCommand, BotCommandScopeDefault
from apscheduler.schedulers.asyncio import AsyncIOScheduler

from LearnBot.middleware.middleware import SchedulerMiddleware
from LearnBot.middleware.db_middleware import DbSession  # 导入DbSession中间件
from LearnBot.others.db_connect import Request, get_db_connector  # 替换为你实际的数据库连接器获取方法

token = "5100032963:***"


class States(StatesGroup):
    first_name = State()
    last_name = State()
    telephone = State()
    complete = State()
    cancel = State()


async def comm(bot: Bot):
    command = [
        BotCommand(
            command='start',
            description='Начало работы',
        ),
        BotCommand(
            command='help',
            description='Помощь',
        ),
    ]

    await bot.set_my_commands(command, BotCommandScopeDefault())


async def on_start(message: types.Message, state: FSMContext, request: Request):
    await message.reply(f"Введите необходимые данные\nВведите имя")
    await request.add_user(message)
    await state.set_state(States.first_name)


async def cancel(message: types.Message, state: FSMContext):
    await state.clear()
    await message.reply("Действие отменено")


def register_fsm(dp: Dispatcher):
    dp.message.register(cancel, States.complete, Text(text='cancel', ignore_case=True))
    dp.message.register(on_start, Command(commands='start'))


async def start():
    try:
        logging.basicConfig(
            level=logging.INFO
        )

        bots = Bot(token)
        dp = Dispatcher()

        # 初始化数据库连接器(替换为你实际的初始化逻辑)
        db_connector = await get_db_connector()
        # 注册DbSession中间件
        dp.message.middleware.register(DbSession(db_connector))
        
        scheduler = AsyncIOScheduler(timezone='Europe/Moscow')
        dp.update.middleware.register(SchedulerMiddleware(scheduler))
        
        # 注册所有handler
        register_fsm(dp)
        
        scheduler.start()
        await comm(bots)  # 调用设置命令的函数
        await dp.start_polling(bots)
    except Exception as ex:
        print(ex)


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

修改后的db_middleware.py

from typing import Callable, Awaitable, Dict, Any

from aiogram import BaseMiddleware
from aiogram.types import Message
from LearnBot.others.db_connect import Request  # 补全Request类的导入


class DbSession(BaseMiddleware):
    def __init__(self, connector):
        self.connector = connector

    async def __call__(self,
        handler: Callable[[Message, Dict[str, Any]], Awaitable[Any]],
        event: Message,
        data: Dict[str, Any],
    ) -> Any:
        async with self.connector.connection() as connect:
            data['request'] = Request(connect)
            return await handler(event, data)

额外注意事项

  • 确保get_db_connector()能返回有效的数据库连接对象,比如基于asyncpg/aiomysql的连接器实例。
  • 确认Request.add_user(message)方法能正确提取用户信息(比如message.from_user.id、message.from_user.first_name等)并插入到数据库中。

内容的提问来源于stack exchange,提问作者JustAnotherVar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 20:15:42