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

如何使用aiogram 3识别群内转发消息的用户并通知管理员

解决aiogram 3识别群内转发消息并提醒管理员的方案

核心逻辑

aiogram 3的Message对象提供了forward_from(转发自普通用户)、forward_from_chat(转发自频道/群组)等属性,只要这些属性不为空,即可判定当前消息是转发内容。

实现步骤

1. 前置准备

  • 将机器人加入目标群组,确保机器人拥有读取消息权限
  • 提前获取管理员的用户ID,以及机器人的TOKEN

2. 完整代码实现

from aiogram import Bot, Dispatcher, types
import asyncio

# 替换为你的机器人TOKEN和管理员ID
BOT_TOKEN = "your_bot_token_here"
ADMIN_ID = 123456789

async def check_forwarded_message(message: types.Message):
    # 跳过机器人自身发送的消息
    if message.from_user.is_bot:
        return
    
    # 判断是否为转发消息
    if message.forward_from or message.forward_from_chat:
        # 组装提醒文本
        alert_content = (
            f"⚠️ 群组内检测到转发消息\n"
            f"群组: {message.chat.title}\n"
            f"发送者: {message.from_user.full_name} (ID: {message.from_user.id})\n"
            f"转发来源: "
        )
        if message.forward_from:
            alert_content += f"用户 {message.forward_from.full_name} (ID: {message.forward_from.id})"
        else:
            alert_content += f"频道/群组 {message.forward_from_chat.title or '未知'} (ID: {message.forward_from_chat.id})"
        
        # 发送提醒给管理员
        await message.bot.send_message(chat_id=ADMIN_ID, text=alert_content)

async def main():
    bot = Bot(token=BOT_TOKEN)
    dp = Dispatcher()
    
    # 注册消息处理器,监听所有群消息
    dp.message.register(check_forwarded_message)
    
    await dp.start_polling(bot)

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

3. 优化与注意事项

  • 若要排除管理员的转发行为,可在函数开头添加判断:
    if message.from_user.id == ADMIN_ID:
        return
    
  • 对于私有频道的转发,message.forward_from_chat.title可能为空,代码中已做兼容处理
  • 确保管理员未开启隐私设置(若开启,需让管理员先主动给机器人发一条消息,否则机器人无法发送消息给对方)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 14:37:03