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

Aiogram CallbackData参数过多及回调过滤器报错求助

解决aiogram CallbackData构建器的两个报错问题

错误原因分析

  1. "Too many arguments were passed!" 报错
    你定义的CallbackData('action', 'sender_id')中,第一个参数是回调数据的前缀(prefix),只有sender_id是合法字段。但调用cb_data.new(action='reply', sender_id=message.chat.id)时额外传入了action参数,超出了定义的字段范围,导致参数不匹配。

  2. "ValueError: Invalid field name 'action'" 报错
    在cb_data.filter(action='reply')中,你尝试过滤action字段,但你的CallbackData定义里并未包含这个字段,系统因此判定字段名无效。

修正方案

修改CallbackData的定义,将action加入字段列表,同时调整前缀(避免和字段名混淆):

cb_data = CallbackData('msg', 'action', 'sender_id')

这样修改后,调用cb_data.new()时传入action和sender_id参数就会匹配定义,过滤器也能正确识别action字段。

完整修正代码

from aiogram import Bot, Dispatcher, executor, types
from aiogram.utils.callback_data import CallbackData
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.state import State, StatesGroup
import config

bot = Bot(token=config.TOKEN)
storage = MemoryStorage()
dp = Dispatcher(bot=bot, storage=storage)


class Form(StatesGroup):
    recipient_id = State()
    message = State()


# 修正CallbackData定义:加入action字段,前缀改为'msg'
cb_data = CallbackData('msg', 'action', 'sender_id')


@dp.message_handler(commands=['start'])
async def start_cmd(message: types.Message, state: FSMContext):
    if message.get_args():
        if message.chat.id == int(message.get_args()):
            return await message.reply(
                text=f"Упс... не думаю, що писати самому собі гарна ідея. \nРозмісти це посилання у себе в Instagram або Telegram нехай тобі пишуть інші. \n\nОсь твоє посилання: \nhttps://t.me/incognito_valentinka_bot/?start={message.chat.id}")
        else:
            await Form.message.set()
            async with state.proxy() as data:
                data['recipient_id'] = message.get_args()

            return await message.answer(
                text="Напиши повідомлення для людини яка розмістила це посилання. \nНапиши все, що думаєшь. \n\n 👀 Ти можешь відправити текст, фото, відео або голосове повідомлення.")

    await message.answer(
        text=f"Привіт! Щоб почати отримувати валентинки розмісти посилання у себе в профілі інстаграм \n\n Ось твоє посилання: 👇 \nhttps://t.me/incognito_valentinka_bot/?start={message.chat.id}")


@dp.callback_query_handler(cb_data.filter(action='reply'))
async def message_reply(query: types.CallbackQuery, callback_data: dict, state: FSMContext):
    print("hello")
    await Form.message.set()
    async with state.proxy() as data:
        data['recipient_id'] = callback_data['sender_id']

    await query.answer(text="Напиши відповідь")


@dp.message_handler(state=Form.message)
async def get_message(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['message'] = message.text

        await bot.send_message(
            chat_id=data['recipient_id'],
            text="<b>Нове повідомлення</b>",
            parse_mode=types.ParseMode.HTML
        )
        inline_keyboard = types.InlineKeyboardMarkup()
        inline_keyboard.row(
            types.InlineKeyboardButton(
                text="Відповісти",
                callback_data=cb_data.new(action='reply', sender_id=message.chat.id)
            )
        )
        await bot.send_message(
            chat_id=data['recipient_id'],
            text=data['message'],
            reply_markup=inline_keyboard
        )

    await message.answer(
        text='<b>Повідомлення доставлено.</b>',
        parse_mode=types.ParseMode.HTML
    )


async def set_my_commands():
    commands = [
        types.BotCommand(command='/start', description='Отримай своє посилання!')
    ]
    await bot.set_my_commands(commands=commands)


async def on_startup(dp):
    print('Starting...')
    await set_my_commands()
    print('Running...')


async def on_shutdown(dp):
    print('Shutting down...')
    print('Stopped!')


if __name__ == '__main__':
    executor.start_polling(
        dispatcher=dp,
        skip_updates=True,
        on_startup=on_startup,
        on_shutdown=on_shutdown,
    )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 02:12:12