Skip to content

优化逻辑 #4

Description

@mrly2333

优化了图片发送逻辑(避免复读图片时报错KeyError: 'file_size')和修改重复信息3次再复读以及重复发送时若信息相同仅复读一次,避免过多的刷屏:
#2
#3

from nonebot import logger
from nonebot.rule import regex
from nonebot.adapters import Event, Message, Bot
from nonebot_plugin_session import extract_session, SessionIdType

from .config import config

plus = on_message(rule=regex(""), priority=config.plus_one_priority, block=False)
msg_dict = {}
tmp_dict = {}  # 新增变量用于保存上一次复读发出的内容

def is_equal(msg1: Message, msg2: Message):
    """判断消息是否相等"""
    if len(msg1) == len(msg2) == 1 and msg1[0].type == msg2[0].type == "image":
        # 使用 get 方法来安全获取 'file_size' 属性
        if msg1[0].data.get("file_size") == msg2[0].data.get("file_size"):
            return True
    if msg1 == msg2:
        return True



@plus.handle()
async def plush_handler(bot: Bot, event: Event):
    global msg_dict
    global tmp_dict

    session = extract_session(bot, event)
    group_id = session.get_id(SessionIdType.GROUP).split("_")[-1]

    # 获取群聊记录
    text_list = msg_dict.get(group_id, None)
    if not text_list:
        text_list = []
        msg_dict[group_id] = text_list

    # 获取当前信息
    msg = event.get_message()

    # 处理消息计数
    if text_list and is_equal(text_list[-1][0], msg):
        text_list[-1] = (text_list[-1][0], text_list[-1][1] + 1)  # 增加计数
    else:
        text_list.append((msg, 1))  # 新消息,重置计数

    # 只在相同消息出现三次时发送
    if text_list[-1][1] >= 3:
        if not is_equal(tmp_dict, msg):  # 防止重复发送
            await plus.send(msg)
            tmp_dict = msg

    # 保持只保存最新的消息
    if len(text_list) > 10:  # 限制列表长度
        text_list.pop(0)  # 移除最旧的消息

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions