from nonebot import logger, on_message
from nonebot.adapters.onebot.v11 import Bot, MessageSegment, Event
from nonebot.plugin import PluginMetadata
from .Reply import Reply, extract_reply
from .make_a_qoute import generate
from nonebot.rule import keyword

__plugin_meta__ = PluginMetadata(
    name="语录",
    description="生成一条语录",
    usage="发送【maq】",
    type="application",
)

rule = keyword('maq')
maq = on_message(rule)


@maq.handle()
async def maq_handle(bot: Bot, ev: Event):
    event = ev.dict()
    try:
        if event['message_type'] != 'group':
            return
        if event['reply']:
            reply = await extract_reply(event, bot)
            if reply.message == -1:
                await maq.finish("请引用文字消息")
            else:
                logger.info("{}, {}, {}".format(reply.user_id, reply.user_card, reply.message))
                image_path = await generate(reply)
                msg = (MessageSegment.image(image_path),)
                await maq.finish(msg)
        else:
            reply = await extract_reply(event, bot)
            if reply.message == -1:
                await maq.finish("请引用文字消息")
            else:
                logger.info("{}, {}, {}".format(reply.user_id, reply.user_card, reply.message))
                image_path = await generate(reply)
                msg = (MessageSegment.image(image_path),)
                await maq.finish(msg)
    except (KeyError, TypeError) as e:
        logger.error(e)
        await maq.finish(str(e))
