Files
NeoBot/plugins/broadcast.py
2026-01-06 23:51:09 +08:00

89 lines
2.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""
管理员专用的广播插件
功能:
- 仅限管理员在私聊中调用。
- 通过回复一条消息并发送指令,将该消息转发给机器人所在的所有群聊。
- 此插件不写入 __plugin_meta__保持隐藏。
"""
from core.command_manager import matcher
from models import MessageEvent
from core.permission_manager import ADMIN
from core.logger import logger
@matcher.command("broadcast", "广播", permission=ADMIN)
async def broadcast_message(event: MessageEvent):
"""
广播指令处理器。
:param event: 消息事件对象。
"""
# 1. 检查是否为私聊消息
# 使用 hasattr 安全地检查 group_id 属性,避免 AttributeError
if hasattr(event, 'group_id') and event.group_id:
# 在群聊中调用时,静默处理,不予响应
return
# 2. 检查是否回复了某条消息
reply = event.reply
if not reply:
await event.reply("请通过“回复”一条您想广播的消息来使用此功能。")
return
# 3. 获取机器人所在的群聊列表
bot = event.bot
try:
group_list = await bot.get_group_list()
if not group_list:
await event.reply("机器人目前没有加入任何群聊。")
return
except Exception as e:
logger.error(f"[Broadcast] 获取群聊列表失败: {e}")
await event.reply(f"获取群聊列表时发生错误,无法广播。错误信息: {e}")
return
# 4. 获取被回复的消息内容
try:
message_data = await bot.get_msg(reply.message_id)
message_content = message_data.get("message", "")
if not message_content:
await event.reply("无法获取被回复的消息内容,广播失败。")
return
except Exception as e:
logger.error(f"[Broadcast] 获取消息内容失败: {e}")
await event.reply(f"获取消息内容时发生错误: {e}")
return
# 5. 遍历所有群聊并发送消息
success_count = 0
failed_count = 0
total_groups = len(group_list)
await event.reply(f"准备向 {total_groups} 个群聊广播消息,请稍候...")
for group in group_list:
group_id = group.group_id
if not group_id:
continue
try:
# 发送消息到群聊
await bot.send_group_msg(
group_id=group_id,
message=message_content
)
success_count += 1
logger.info(f"[Broadcast] 已成功将消息发送至群聊: {group_id}")
except Exception as e:
failed_count += 1
logger.error(f"[Broadcast] 发送消息至群聊 {group_id} 失败: {e}")
# 6. 向管理员报告结果
report_message = (
f"广播任务完成。\n"
f"总群聊数: {total_groups}\n"
f"成功: {success_count}\n"
f"失败: {failed_count}"
)
await event.reply(report_message)