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

如何编写Aiogram 3过滤器:仅执行指定命令或无命令场景

Aiogram 3 实现指定命令或无命令时触发的过滤器

要实现仅当消息包含指定命令/mycommand或无任何命令时触发的过滤器,你需要修正原逻辑的判断方式,原写法的问题在于对entities的遍历判断有误,Aiogram的F表达式支持更精准的条件组合:

正确的F表达式过滤器写法

from aiogram import F, types
from aiogram.types import MessageEntityType

@dp.message(
    F.text,
    (F.entities & F.entities.type == MessageEntityType.BOT_COMMAND).not_() 
    | F.text.startswith("/mycommand")
)
async def handle_target_message(message: types.Message):
    # 此处编写你的业务逻辑
    await message.answer("触发成功")

逻辑拆解

  • F.text:确保消息存在文本内容,避免无文本的消息触发
  • (F.entities & F.entities.type == MessageEntityType.BOT_COMMAND).not_():判断消息中不存在任何机器人命令类型的实体,即无命令的情况
  • |:逻辑或运算符,满足「无命令」或「消息文本以指定命令/mycommand开头」任一条件即可触发

自定义过滤器写法(更直观)

如果觉得F表达式不够直观,可以自定义过滤器函数,逻辑更清晰:

from aiogram.filters import Filter
from aiogram.types import Message, MessageEntityType

class CommandOrNoCommandFilter(Filter):
    def __init__(self, target_command: str):
        self.target_command = target_command

    async def __call__(self, message: Message) -> bool:
        # 检查消息是否包含命令实体
        has_bot_commands = any(
            entity.type == MessageEntityType.BOT_COMMAND 
            for entity in message.entities or []
        )
        # 无命令则返回True
        if not has_bot_commands:
            return True
        # 有命令则检查是否是指定命令
        return message.text.startswith(self.target_command)

# 使用自定义过滤器
@dp.message(CommandOrNoCommandFilter("/mycommand"))
async def handle_target_message(message: types.Message):
    await message.answer("触发成功")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 04:52:47