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

关于Telegram机器人禁言功能及aiogram聊天类型过滤的技术问询

问题1:群组限时禁言代码不生效的解决方法

你的代码问题在于直接将布尔值传给permissions参数,aiogram的restrict_chat_member方法要求permissions必须是ChatPermissions类的实例,而非简单布尔值,同时限时禁言需要指定until_date参数。

修复步骤:

  1. 导入ChatPermissions类
  2. 构造权限对象,明确关闭对应权限
  3. 添加until_date参数设置禁言时长(Unix时间戳格式)

示例代码:

import time
from aiogram.types import ChatPermissions

# 构造禁言权限,按需关闭对应权限
restricted_perms = ChatPermissions(
    can_send_messages=False,
    can_send_media_messages=False,
    can_send_polls=False,
    can_send_other_messages=False,
    can_change_info=False,
    can_invite_users=False,
    can_pin_messages=False
)

# 限时60秒禁言,until_date为当前时间+60秒的时间戳
await bot.restrict_chat_member(
    chat_id=message.chat.id,
    user_id=user_id,
    permissions=restricted_perms,
    until_date=int(time.time()) + 60
)

额外注意:确保机器人在群组中拥有限制成员的管理员权限,否则操作会失败。

问题2:aiogram过滤指定聊天类型的命令

aiogram有两种常用方式实现该需求,对应不同版本的写法:

方式一:使用内置ChatTypeFilter(推荐,aiogram 3.x+)

from aiogram import Router
from aiogram.filters import ChatTypeFilter
from aiogram.types import Message, ChatType

router = Router()

@router.message(
    commands=['balance'],
    ChatTypeFilter([ChatType.PRIVATE, ChatType.GROUP, ChatType.SUPERGROUP])
)
async def handle_balance(message: Message):
    # 编写你的余额查询逻辑
    await message.answer("你的余额信息已查询")

方式二:使用func参数(类似telebot写法,兼容aiogram 2.x/3.x)

# aiogram 3.x用router,2.x替换为@bot.message_handler
@router.message(
    commands=['balance'],
    func=lambda msg: msg.chat.type in ['private', 'group', 'supergroup']
)
async def handle_balance(message: Message):
    await message.answer("你的余额信息已查询")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 05:24:57