コード例 #1
0
ファイル: TalkToMeListener.py プロジェクト: alcmoe/TakeItEasy
 def atOrQuoteFilter(message: MessageChain):
     if not message.has(Quote) and not message.has(At):
         raise ExecutionStop()
     if plains := message.get(Plain):
         if any(text.__dict__['text'].strip() in
                PictureRipperListener.QUOTE_COMMANDS for text in plains):
             raise ExecutionStop()
コード例 #2
0
    async def handle(self, app: GraiaMiraiApplication, message: MessageChain,
                     group: Group, member: Member):
        message_text = "".join([plain.text
                                for plain in message.get(Plain)]).strip()
        if message_text == "幻影" or message_text == "彩色幻影":
            await update_user_call_count_plus1(group, member,
                                               UserCalledCount.functions,
                                               "functions")
            if len(message.get(Image)) != 2:
                return MessageItem(
                    MessageChain.create(
                        [Plain(text="非预期图片数!请按照 `显示图 隐藏图` 顺序发送,一共两张图片")]),
                    QuoteSource(GroupStrategy()))
            else:
                display_img = message[Image][0]
                async with aiohttp.ClientSession() as session:
                    async with session.get(url=display_img.url) as resp:
                        display_img = IMG.open(BytesIO(await resp.read()))

                hide_img = message[Image][1]
                async with aiohttp.ClientSession() as session:
                    async with session.get(url=hide_img.url) as resp:
                        hide_img = IMG.open(BytesIO(await resp.read()))

                return await self.get_message(group, member, display_img,
                                              hide_img)
        else:
            return await super().handle(app, message, group, member)
コード例 #3
0
 def quoteFilter(self, message: MessageChain):
     if not message.has(Quote):
         raise ExecutionStop()
     if plains := message.get(Plain):
         if all(text.__dict__['text'].strip() not in self.QUOTE_COMMANDS
                for text in plains):
             raise ExecutionStop()
コード例 #4
0
    async def handle(self, app: GraiaMiraiApplication, message: MessageChain,
                     group: Group, member: Member):
        if apps := message.get(App):
            app_json = json.loads(apps[0].content)
            if app_json[
                    "prompt"] == "[QQ小程序]哔哩哔哩" or "meta" in app_json and "detail_1" in app_json[
                        "meta"] and app_json["meta"]["detail_1"][
                            "title"] == "哔哩哔哩":
                short_url = app_json["meta"]["detail_1"]["qqdocurl"]

                async with aiohttp.ClientSession() as session:
                    async with session.get(url=short_url,
                                           allow_redirects=False) as resp:
                        result = (await resp.read()).decode("utf-8")
                bv_url = result.split("\"")[1].split("?")[0].split(
                    "/")[-1].strip()
                print(bv_url)

                bilibili_video_api_url = f"http://api.bilibili.com/x/web-interface/view?aid={self.bv_to_av(bv_url)}"

                async with aiohttp.ClientSession() as session:
                    async with session.get(url=bilibili_video_api_url) as resp:
                        result = (await resp.read()).decode('utf-8')
                result = json.loads(result)
                return MessageItem(await self.generate_messagechain(result),
                                   Normal(GroupStrategy()))

            else:
                return await super().handle(app, message, group, member)
コード例 #5
0
async def xiaolaodi(app: GraiaMiraiApplication, group: Group, message: MessageChain, member: Member):
    if '小老弟' in message.asDisplay() and message.has(At):
        xiaolaodi = IMG.open(Path(__file__).parent/'小老弟.png')
        if (at_u := message.get(At)[0].target) == app.connect_info.account:
            text = '我哪里像小老弟了,小老弟'
            to = member.id
            user = at_u
        else:
            text = ''
            to = at_u
            user = member.id

        user_pic = f'http://q1.qlogo.cn/g?b=qq&nk={user}&s=640'
        to_pic = f'http://q1.qlogo.cn/g?b=qq&nk={to}&s=640'
        async with aiohttp.request("GET",user_pic) as r:
            user_pic = await r.read()
            user_pic = IMG.open(BytesIO(user_pic))
        async with aiohttp.request("GET",to_pic) as r:
            to_pic = await r.read()
            to_pic = IMG.open(BytesIO(to_pic))
        user_box = (18,9,87,78)
        to_box = (173,23,232,82)
        user_pic = user_pic.resize((user_box[2] - user_box[0],
                                    user_box[3] - user_box[1]))
        to_pic = to_pic.resize((to_box[2] - to_box[0],
                                to_box[3] - to_box[1]))
        xiaolaodi.paste(user_pic,user_box)
        xiaolaodi.paste(to_pic,to_box)
        out = BytesIO()
        xiaolaodi.save(out, format='PNG')
        await app.sendGroupMessage(group, MessageChain.create([
            Plain(text = text),
            Image.fromUnsafeBytes(out.getvalue())]))
コード例 #6
0
 async def handle(self, app: GraiaMiraiApplication, message: MessageChain, group: Group, member: Member):
     if message.has(At) and message.get(At)[0].target == get_config("BotQQ"):
         await update_user_call_count_plus1(group, member, UserCalledCount.at, "at")
         content = "".join(plain.text for plain in message.get(Plain)).strip().replace(" ", ",")
         set_result(message, await self.get_reply(member.id, group.id, content))
     else:
         return None
コード例 #7
0
async def nbnhhsh(message: MessageChain, app: GraiaMiraiApplication,
                  group: Group):
    try:
        text = message.get(Plain)[0].asDisplay()
    except IndexError:
        return
    if 'nbnhhsh' in text and message.has(Quote):
        orig = message.get(Quote)[0].origin
        text = orig.get(Plain)[0].asDisplay()
        await app.sendGroupMessage(
            group,
            MessageChain.create([Plain(text + ":" + await guess(text))]))
コード例 #8
0
ファイル: define_controller.py プロジェクト: ztc-git/qq-bot
    def write_define(self, message: MessageChain):
        msg = message.asDisplay().split(' ', 3)
        if len(msg) == 2:
            Msg = '? 定义啥你倒是说啊'
        elif len(msg) == 3:
            try:
                del self.define_data[msg[2]]
                Msg = '定义清除成功'
            except KeyError:
                Msg = '没有这个定义啊喂'
        elif len(msg) == 4:
            if message.has(Image):
                image = Image()
                image.url = message.get(Image)[0].url
                data = [image.url]
            else:
                data = msg[3]

            if msg[2] in self.define_data:
                Msg = '定义覆盖成功'
            else:
                Msg = '定义成功'
            self.define_data[msg[2]] = data

        self.db.write_define_to_file(self.define_data)
        return Msg
コード例 #9
0
 async def handle(self, app: GraiaMiraiApplication, message: MessageChain, group: Group, member: Member):
     message_text = message.asDisplay()
     if message.has(At) and message_text.startswith("摸"):
         await update_user_call_count_plus1(group, member, UserCalledCount.functions, "functions")
         set_result(message, await self.petpet(message.get(At)[0].target))
     else:
         return None
コード例 #10
0
 async def record(message: MessageChain, group: Group, member: Member):
     await update_user_call_count_plus1(group, member,
                                        UserCalledCount.chat_count,
                                        "chat_count")
     content = "".join([plain.text for plain in message.get(Plain)])
     filter_words = re.findall(r"\[mirai:(.*?)\]", content, re.S)
     for i in filter_words:
         content = content.replace(f"[mirai:{i}]", "")
     if content:
         seg_result = jieba.lcut(content)
         # dictionary = corpora.Dictionary([seg_result])
         # new_corpus = [dictionary.doc2bow(seg_result)]
         # # if not os.path.exists(f"./statics/model/tf_idf_model.tfidf"):
         # #     os.mknod("./model/statics/tf_idf_model.tfidf")
         # tfidf = models.TfidfModel(models.TfidfModel.load("./statics/model/tf_idf_model.tfidf") + new_corpus)
         # with open(f"./statics/model/tf_idf_model.tfidf", "w") as w:
         #     tfidf.save(w)
         if not seg_result:
             return None
         await orm.add(
             ChatRecord, {
                 "time": datetime.datetime.now(),
                 "group_id": group.id,
                 "member_id": member.id,
                 "content": content,
                 "seg": "|".join(seg_result)
             })
コード例 #11
0
 async def record(self, message: MessageChain, group: Group,
                  member: Member):
     await update_user_call_count_plus1(group, member,
                                        UserCalledCount.chat_count,
                                        "chat_count")
     content = "".join([plain.text for plain in message.get(Plain)])
     filter_words = re.findall(r"\[mirai:(.*?)\]", content, re.S)
     for i in filter_words:
         content = content.replace(f"[mirai:{i}]", "")
     if content:
         seg_result = jieba.lcut(content)
         if not seg_result:
             return None
         new_id = list(
             orm.fetchone(
                 select(ChatRecord.id).order_by(desc(ChatRecord.id)), 1))
         new_id = new_id[0][0] + 1 if new_id else 1
         try:
             orm.add(
                 ChatRecord, {
                     "id": new_id,
                     "time": datetime.datetime.now(),
                     "group_id": group.id,
                     "member_id": member.id,
                     "content": content,
                     "seg": "|".join(seg_result)
                 })
         except Exception as e:
             logger.error(traceback.format_exc())
             orm.session.rollback()
コード例 #12
0
async def groupMessage(app: GraiaMiraiApplication, group: Group,
                       member: Member, message: MessageChain):
    if message.has(At):
        if message.get(At)[0].target == 993422335:
            str_reply = reply(message[Plain][0].text.strip())
            await app.sendGroupMessage(
                group,
                MessageChain.create([Plain(str_reply + ' '),
                                     At(member.id)]))
コード例 #13
0
ファイル: main.py プロジェクト: EricTianC/TaoTao
async def group_message_listener(
    message: MessageChain,
    app: GraiaMiraiApplication,
    group: Group,
    member: Member,
):
    await judge(message.asDisplay(), group, member)
    if message.has(Voice):
        log.CustomLogger.debug(group, message.get(Voice))
        await voice_get(message, member, group, app)
コード例 #14
0
async def jbK(app: GraiaMiraiApplication, group: Group, member: Member,
              message: MessageChain):
    if not message.has(At) or message.has(Image):
        return
    if message.get(
            Image)[0].imageId == "{7F7177D2-D24A-93F5-32BA-C50CCFD02F70}.jpg":
        at = message.get(At)[0]
        member_at = await app.getMember(group, at.target)
        name = "{}({})".format(member_at.name, at.target)
        if not jb.get(group.id):
            jb[group.id] = {}
        if not jb[group.id].get(name):
            jb[group.id][name] = 0
        jb[group.id][name] += 0.5
        await app.sendGroupMessage(
            group,
            MessageChain.create(
                [At(member.id),
                 Plain(f" 砍了下{name}的jb, {name}的jb-0.5")]),
        )
コード例 #15
0
def mute_member(app, group: Group, msg: MessageChain):
    if not msg.has(At):
        return
    mutelist = []
    time = 0
    text = msg.asDisplay().split(' ')
    for at in msg.get(At):
        mutelist.append(at.target)
    for i in text:
        if is_number(i):
            time = max(time, float(i))
    mutelist.sort()
    asyncio.create_task(set_mute(app, group, mutelist, time))
コード例 #16
0
 async def handle(app: GraiaMiraiApplication, message: MessageChain,
                  group: Group, member: Member):
     if message.asDisplay().startswith("说 "):
         text = ''.join([plain.text for plain in message.get(Plain)
                         ])[2:].replace(" ", ',')
         voice = await SpeakHandler.get_voice(text)
         if isinstance(voice, str):
             return MessageItem(MessageChain.create([Plain(text=voice)]),
                                QuoteSource(GroupStrategy()))
         elif isinstance(voice, bytes):
             voice_element = await app.uploadVoice(await
                                                   silkcoder.encode(voice))
             return MessageItem(MessageChain.create([voice_element]),
                                Normal(GroupStrategy()))
コード例 #17
0
async def jba(app: GraiaMiraiApplication, group: Group, member: Member,
              message: MessageChain):
    if message.has(Image):
        if (message.get(Image)[0].imageId ==
                "{7F7177D2-D24A-93F5-32BA-C50CCFD02F70}.jpg"):
            name = "{}({})".format(member.name, member.id)
            if not jb.get(group.id):
                jb[group.id] = {}
            if not jb[group.id].get(name):
                jb[group.id][name] = 0
            jb[group.id][name] += 1
            await app.sendGroupMessage(
                group, MessageChain.create([At(member.id),
                                            Plain(" 你的jb-1")]))
コード例 #18
0
ファイル: main.py プロジェクト: Iydon/info_qq_bot
async def group_message_listener(app: GraiaMiraiApplication, group: Group,
                                 member: Member, message: MessageChain):
    content = message.asDisplay().strip()
    if group.id in information_groups:  # 信息群
        # 特征记录:大喘气
        global aml
        if member.id != aml[group.id][0]:
            aml[group.id] = [member.id, 0, 0]
        aml[group.id][1] += len(content)
        aml[group.id][2] += 1
        caml = aml[group.id]  # current aml
        # 判断信息群是否存在低效情况
        tips = ''
        if all(isinstance(element, (Source, Face)) for element in message):
            tips = '【自动回复】信息群请不要单发表情哟~(如有误判请忽略)'
        elif len(content) >= 3 and len(set(content)) == 1:  # 避免 '???' '。。。' 等
            tips = '【自动回复】信息群请不要重复单字哟~(如有误判请忽略)'
        elif caml[2] >= 3 and caml[1] / caml[2] < 10:
            tips = '【自动回复】信息群请避免大喘气,否则容易刷丢重要信息(如有误判请忽略)'
        if tips:
            await app.sendTempMessage(
                group,
                member,
                MessageChain.create([Plain(tips)]),
                quote=message.get(Source)[0],
            )
            return
    return_ = process(content)
    if return_:
        # 可能由于风控原因,偶尔无法在群里发言,因此改为私聊回复
        # await app.sendGroupMessage(
        #     group, MessageChain.create(return_), quote=message.get(Source)[0]
        # )
        await app.sendTempMessage(group,
                                  member,
                                  MessageChain.create(return_),
                                  quote=message.get(Source)[0])
コード例 #19
0
 async def handle(app: GraiaMiraiApplication, message: MessageChain,
                  group: Group, member: Member):
     legal_type = ("setu", "setu18", "real", "realHighq", "wallpaper",
                   "sketch")
     if re.match(
             r"添加(setu|setu18|real|realHighq|wallpaper|sketch)图片(\[图片])+",
             message.asDisplay()):
         if not user_permission_require(group, member, 2):
             return MessageItem(
                 MessageChain.create([Plain(text="你没有权限,爬!")]),
                 Normal(GroupStrategy()))
         image_type = re.findall(r"添加(.*?)图片(\[图片])+", message.asDisplay(),
                                 re.S)[0][0]
         if image_type not in legal_type:
             return MessageItem(
                 MessageChain.create([
                     Plain(
                         text=f"非法图片类型!\n合法image_type:{'、'.join(legal_type)}"
                     )
                 ]), QuoteSource(GroupStrategy()))
         if path := get_config(f"{image_type}Path"):
             if os.path.exists(path):
                 try:
                     await ImageAdderHandler.add_image(
                         path, message.get(Image))
                 except Exception as e:
                     logger.error(traceback.format_exc())
                     return MessageItem(
                         MessageChain.create(
                             [Plain(text="出错了呐~请查看日志/控制台输出!")]),
                         Normal(GroupStrategy()))
                 return MessageItem(
                     MessageChain.create([
                         Plain(
                             text=f"保存成功!共保存了{len(message.get(Image))}张图片!")
                     ]), Normal(GroupStrategy()))
             else:
                 return MessageItem(
                     MessageChain.create([
                         Image.fromLocalFile(
                             f"{os.getcwd()}/statics/error/path_not_exists.png"
                         )
                     ]), QuoteSource(GroupStrategy()))
         else:
             return MessageItem(
                 MessageChain.create(
                     [Plain(text=f"无{image_type}Path项!请检查配置!")]),
                 QuoteSource(GroupStrategy()))
コード例 #20
0
async def petpet_generator(app: GraiaMiraiApplication, message: MessageChain,
                           member: Member, group: Group):
    message_text = message.asDisplay()
    if message.has(At) and message_text.startswith(
            "摸") or message_text.startswith("摸 "):
        await petpet(message.get(At)[0].target)
        try:
            await app.sendGroupMessage(
                group,
                MessageChain.create([
                    Image.fromLocalFile(
                        f"./plugins/PetPet/tempPetPet-{message.get(At)[0].target}.gif"
                    )
                ]))
        except AccountMuted:
            pass
コード例 #21
0
ファイル: __init__.py プロジェクト: purofle/Black-Cat-qqbot
async def petpet_generator(app: GraiaMiraiApplication, message: MessageChain,
                           group: Group):
    message_text = message.asDisplay()
    if message.has(At) and message_text.startswith(
            "摸") or message_text.startswith("摸 "):
        if not os.path.exists("functions/PetPet/temp"):
            os.mkdir("functions/PetPet/temp")
        await petpet(message.get(At)[0].target)
        try:
            await app.sendGroupMessage(
                group,
                MessageChain.create([
                    Image.fromLocalFile(
                        f"functions/PetPet/temp/tempPetPet-{message.get(At)[0].target}.gif"
                    )
                ]))
        except AccountMuted:
            pass
コード例 #22
0
async def group_message_handler_OCRandAT(
    message: MessageChain,
    app: GraiaMiraiApplication,
    group: Group, member: Member,
    saying: MessageChain,message_info: GroupMessage
):
    #print(message_info.sender.id)
    #print(message.has(Image))

    if message_info.sender.id in [1251811859, 81414770, 961836880] and message.has(Image):
        # 保存图像
        groupList = await app.groupList()
        print("group" , message_info.sender.group.id)
        memberList = await app.memberList(message_info.sender.group.id)
        # print(groupList)
        # print(memberList)
        # print(type(memberList))
        imgs = message.get(Image)
        for i in imgs:
            async with aiohttp.ClientSession() as session:
                async with session.get(url=i.url) as resp:
                    img_content = await resp.read()
            image = IMG.open(BytesIO(img_content))
            image.save('11.png')
            # print(type(imgs))#it is a list
            content = ocr.ocr('11.png')
            print(content)
            #await app.sendGroupMessage(group, MessageChain.create([Plain(content)]))
            if "学生列表" in content or "技术支持" in content or "股份有限公司" in content:
                result_num = ocr.school_number(content)
                #print(result)
                (result,err) = ocr.at_schoolnum(result_num,memberList)
                msg = [Plain(f"Tip:保持图片学号上方无遮挡可以提高识别准确率\n请以下同学支付宝打卡\n")]
                for j in result:
                    msg.append(At(j))
                if len(err) != 0:
                    msg.append(Plain("\n群昵称中含有8位数学号便可正确识别身份啦~\n请手动@以下未匹配同学并修改其群昵称 \n"))
                    for j in err:
                        msg.append(Plain(j))
                        msg.append(Plain(f"\n"))
                await app.sendGroupMessage(group, MessageChain.create(msg))
            '''
コード例 #23
0
async def messagechain_to_img(
    message: MessageChain,
    max_width: int = 1080,
    font_size: int = 40,
    spacing: int = 15,
    padding_x: int = 20,
    padding_y: int = 15,
    img_fixed: bool = False,
    font_path: str = "./simhei.ttf",
    save_path: str = "./statics/temp/tempMessageChainToImg.png"
) -> MessageChain:
    """
    将 MessageChain 转换为图片,仅支持只含有本地图片/文本的 MessageChain

    Args:
        message: 要转换的MessageChain
        max_width: 最大长度
        font_size: 字体尺寸
        spacing: 行间距
        padding_x: x轴距离边框大小
        padding_y: y轴距离边框大小
        img_fixed: 图片是否适应大小(仅适用于图片小于最大长度时)
        font_path: 字体文件路径
        save_path: 图片存储路径

    Examples:
        msg = await messagechain_to_img(message=message)

    Returns:
        MessageChain (内含图片Image类)
    """
    font = ImageFont.truetype(font_path, font_size, encoding="utf-8")
    message = message.asMerged()
    elements = message.__root__

    plains = message.get(Plain)
    text_gather = "\n".join([plain.text for plain in plains])
    print(
        max(font.getsize(text)[0]
            for text in text_gather.split("\n")) + 2 * padding_x)
    final_width = min(
        max(font.getsize(text)[0]
            for text in text_gather.split("\n")) + 2 * padding_x, max_width)
    text_width = final_width - 2 * padding_x
    text_height = (font_size + spacing) * await get_final_text_lines(
        text_gather, text_width, font)
    # text_height = (font_size + spacing) * sum([await get_final_text_lines(plain.text, text_width, font)for plain in plains])

    img_height_sum = 0
    temp_img_list = []
    images = message.get(Image_LocalFile)
    for image in images:
        if isinstance(image, Image_LocalFile):
            # print(img_height_sum)
            temp_img = IMG.open(image.filepath)
            # print(temp_img.size)
            img_width, img_height = temp_img.size
            temp_img_list.append(
                temp_img := temp_img.resize((
                    int(final_width - 2 * spacing),
                    int(
                        float(img_height * (final_width - 2 * spacing)) /
                        float(img_width)))) if img_width > final_width -
                2 * spacing or (img_fixed and img_width < final_width -
                                2 * spacing) else temp_img)
            img_height_sum = img_height_sum + temp_img.size[1]
            # print(temp_img.size[1])
            # print(img_height)
        else:
            raise Exception("messagechain_to_img:仅支持本地图片即Image_LocalFile类的处理!")
    final_height = 2 * padding_y + text_height + img_height_sum
    picture = IMG.new('RGB', (final_width, final_height), (255, 255, 255))
    draw = ImageDraw.Draw(picture)
    present_x = padding_x
    present_y = padding_y
    image_index = 0
    # print(temp_img_list)
    for element in elements:
        if isinstance(element, Image_LocalFile):
            print(f"adding img {image_index}")
            picture.paste(temp_img_list[image_index], (present_x, present_y))
            present_y += (spacing + temp_img_list[image_index].size[1])
            image_index += 1
        elif isinstance(element, Plain):
            print(f"adding text '{element.text}'")
            # if font.getsize(element.text)[0] <= text_width:
            #     draw.text((present_x, present_y), element.text, font=font, fill=(0, 0, 0))
            # else:
            for char in element.text:
                if char == "\n":
                    present_y += (font_size + spacing)
                    present_x = padding_x
                    continue
                if present_x + font.getsize(char)[0] > text_width:
                    present_y += (font_size + spacing)
                    present_x = padding_x
                draw.text((present_x, present_y),
                          char,
                          font=font,
                          fill=(0, 0, 0))
                present_x += font.getsize(char)[0]
            present_y += (font_size + spacing)
            present_x = padding_x

    # print(f"textHeight: {text_height}\nimgHeight: {img_height}\nfinalHeight: {final_height}")
    # print(f"present_x: {present_x}, present_y: {present_y}")
    picture.save(save_path)
    print(f"process finished! Image saved at {save_path}")
    return MessageChain.create([Image.fromLocalFile(save_path)])
コード例 #24
0
async def group_message_handler(app: GraiaMiraiApplication,
                                message: MessageChain, group: Group,
                                member: Member):

    url = ""
    b23_url = ""  # 先申请好两种要用的url
    if Msg_element.Xml in message:
        xml = message.get(Xml)
        xml_msg = etree.fromstring(
            message.get(Msg_element.Xml)[0].xml.encode('utf-8'))  #将xml进行解码
        url = xml_msg.xpath('/msg/@url')[0]  #这是xml中包含bv号的链接
        result = re.search(bvpattern, url)  #进行bv号的一个匹配
    else:
        result = re.search(bvpattern, message.asDisplay())  #说明是纯文本,直接找bv号

    if result != None:  #匹配到了的情况:说明是用电脑端的链接分享的
        BVname = result.group()
        print(BVname)
        videoInformation = bvcrawler(BVname)
        await app.sendGroupMessage(
            group,
            MessageChain.create([
                Image.fromNetworkAddress(videoInformation['cover_url']),
                Plain(videoInformation['information'])
            ]))
    else:  #没有匹配到bv号然而又是xml,说明这不是电脑端分享的链接,而是iphone分享的链接,这里的url是b23短链接
        if url != "":  #因为url初值是空,所以这里做一个判断避免每一次输入一个信息就进行查找
            b23_url = url
            resp = requests.get(
                b23_url, allow_redirects=False)  #向b23短链接发送请求,然后阻止其进行重定向到网站上去
            redirect_url = resp.headers.get('Location')  #得到重定向后的url
            result = re.search(bvpattern, redirect_url)  #得到重定向后的bv号
            if result != None:
                BVname = result.group()
                print(BVname)
                videoInformation = bvcrawler(BVname)
                await app.sendGroupMessage(
                    group,
                    MessageChain.create([
                        Image.fromNetworkAddress(
                            videoInformation['cover_url']),
                        Plain(videoInformation['information'])
                    ]))

    if Msg_element.App in message:  #说明是用手机分享的,是一个json格式的消息,我们可以从中解码得到b23短链接
        json_msg = json.loads(message.get(
            Msg_element.App)[0].content)  #这里的json格式要这样解码
        name = json_msg['desc']
        if name == "哔哩哔哩":  #如果这里的name叫哔哩哔哩,那说明是手机客户端分享的小程序
            b23_url = json_msg['meta']['detail_1']['qqdocurl']  #b23_url此时在这里
        else:  #这里的name不是叫哔哩哔哩了,准确来说是为空,那说明是ipad的HD客户端分享的小程序
            b23_url = json_msg['meta']['news']['jumpUrl']  #b23_url此时又是在这里
        resp = requests.get(b23_url,
                            allow_redirects=False)  #和上面一样的http302拦截,然后得到bv号
        redirect_url = resp.headers.get('Location')
        result = re.search(bvpattern, redirect_url)
        if result != None:
            BVname = result.group()
            print(BVname)
            videoInformation = bvcrawler(BVname)
            await app.sendGroupMessage(
                group,
                MessageChain.create([
                    Image.fromNetworkAddress(videoInformation['cover_url']),
                    Plain(videoInformation['information'])
                ]))

    if message.has(At):
        flag = 0
        for at in message.get(At):
            if at.target == 5980403:
                flag = 1
        if flag == 0:
            return
        else:
            msg = message.asSerializationString()
            message_a = MessageChain.create([
                Plain("消息监听:\n%s(%d)在群%s(%d)中对我说:\n%s" %
                      (member.name, member.id, group.name, group.id,
                       message.asDisplay()))
            ])
            message_b = message.asSendable()
            message_a.plus(message_b)
            for i in range(0, len(message_a.__root__)):
                if message_a.__root__[i].type == 'At':
                    message_a.__root__[i] = Plain(
                        message_a.__root__[i].display)

            await app.sendFriendMessage(5980403, message_a)

    if message.asDisplay() == "help":
        sstr = "目前已经公开的功能有:" + "\n\n"
        sstr += "①打招呼功能,输入hi说不定可以得到妹妹的回应哦~" + "\n\n"
        sstr += "②查bv号和av号的功能,并且能够解析任何形式分享的b站视频,能够显示视频的详细信息~" + "\n\n"
        sstr += "③随机提供涩图的功能,输入‘色图时间’或者‘来点涩图’就可以随机发送一张图片了~" + "\n\n"
        sstr += "④整点报时功能~\n\n"
        sstr += "⑤提供b站车万区周榜功能~\n\n"
        sstr += "⑥碧蓝航线实时推送功能,并且输入'碧蓝航线最新动态'可以得到碧蓝航线官方账号发送的最新动态哦~\n\n"
        sstr += "⑦点歌功能。输入【点歌 xxx】就可以查找到你喜欢的歌曲哦~\n"
        sstr += "凛夜sama赛高!(不要忘了所有的功能都是凛夜亲手敲的代码哦)"
        await app.sendGroupMessage(group, MessageChain.create([Plain(sstr)]))

    if message.asDisplay() == "hi":
        if (member.id == 5980403):
            await app.sendGroupMessage(
                group, MessageChain.create([At(5980403),
                                            Plain(" 哥哥爱死你了mua")]))
        elif (member.id == 349468958):
            await app.sendGroupMessage(
                group, MessageChain.create([Plain("哥哥我也爱你呢❤")]))
        elif (member.id == 865734287):
            await app.sendGroupMessage(
                group,
                MessageChain.create([Plain("mu..(害怕)mua?"),
                                     Face(faceId=111)]))
        elif (member.id == 744938425):
            await app.sendGroupMessage(
                group,
                MessageChain.create([
                    At(744938425),
                    Plain(" 欧尼酱要吃饭呢,要洗澡呢,还是要先吃我呢"),
                    Face(faceId=111)
                ]))
        else:
            await app.sendGroupMessage(
                group, MessageChain.create([At(member.id),
                                            Plain("hi~")]))

    if message.asDisplay() == "晚安":
        if (member.id == 5980403):
            await app.sendGroupMessage(
                group,
                MessageChain.create(
                    [At(5980403), Plain(" 哥哥晚安"),
                     Face(faceId=75)]))
        else:
            await app.sendGroupMessage(
                group, MessageChain.create([At(member.id),
                                            Plain(" 晚安~")]))

    if message.asDisplay() == "草" or message.asDisplay() == "艹":
        if random.random() <= 0.25:
            await app.sendGroupMessage(group,
                                       MessageChain.create([Plain("草")]))
        else:
            return

    if (member.id != 2083664136 and member.id != 2079373402):
        if message.asDisplay().startswith(
                "AV") or message.asDisplay().startswith("av"):
            videoInformation = avcrawler(message.asDisplay())
            await app.sendGroupMessage(
                group,
                MessageChain.create([
                    Image.fromNetworkAddress(videoInformation['cover_url']),
                    Plain(videoInformation['information'])
                ]))

    if message.asDisplay() == "色图时间" or message.asDisplay(
    ) == "来点涩图" or message.asDisplay() == "来点色图":
        url = "https://api.nmb.show/1985acg.php"
        conn = aiohttp.TCPConnector(ssl=False)
        async with aiohttp.request('GET', url, connector=conn) as resp:
            content = await resp.read()
        try:
            await app.sendGroupMessage(
                group, MessageChain.create([Image.fromUnsafeBytes(content)]))
        except:
            await app.sendGroupMessage(
                group,
                MessageChain.create([Plain("该图片无法显示qwq"),
                                     Face(faceId=107)]))

    if message.asDisplay() == "来点辉夜" or message.asDisplay() == "辉夜图":
        kaguyaDir = "./Kaguya"
        kaguyaNames = []
        for parent, dirnames, filenames in os.walk(kaguyaDir):
            kaguyaNames = filenames
        x = random.randint(0, len(kaguyaNames) - 1)
        pictureLocation = kaguyaDir + "/" + kaguyaNames[x]
        await app.sendGroupMessage(
            group, MessageChain.create([Image.fromLocalFile(pictureLocation)]))

    if message.asDisplay() == "车万周榜" or message.asDisplay() == "东方周榜":
        msg = Touhou()
        await app.sendGroupMessage(group, MessageChain.create([Plain(msg)]))

    if message.asDisplay() == "维护" and member.id == 5980403:
        msg = "就算是机器人的妹妹我也要休息了呢qwq,凛夜哥哥要对我进行功能维护了,大家好好期待吧~"
        groups = [372733015, 766517688, 875626950, 862315052, 729801800]
        for group in groups:
            await app.sendGroupMessage(group,
                                       MessageChain.create([Plain(msg)]))

    if message.asDisplay() == "停止维护" and member.id == 5980403:
        msg = "凛夜哥哥对我的维护已经结束了,我又可以继续被大家正常使用了呢~(羞涩)"
        groups = [372733015, 766517688, 875626950, 862315052, 729801800]
        for group in groups:
            await app.sendGroupMessage(group,
                                       MessageChain.create([Plain(msg)]))

    if message.asDisplay() == "碧蓝航线最新动态":
        await blhx(app, group)

    if message.asDisplay() == "lex凉了没" or message.asDisplay() == "lex":
        lexurl = "https://api.bilibili.com/x/relation/stat?vmid=777536"
        headers = {
            'User-Agent':
            'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1',
        }
        msg = requests.get(lexurl, headers=headers).json()
        followers = msg['data']['follower']
        string = "lex的粉丝数已经掉到" + str(followers) + "了~"
        await app.sendGroupMessage(group, MessageChain.create([Plain(string)]))

    if member.id == 5980403 and message.asDisplay() == '贴吧签到':
        ua = Faker()
        headers = {
            'cookie':
            "BIDUPSID=9D96E01732C84E3EF46E6D69F715EB8E; PSTM=1574597643; bdshare_firstime=1574667391465; rpln_guide=1; H_WISE_SIDS=147935_162057_156287_159609_162914_155225_161299_163303_161266_162371_159382_159937_161421_157263_161419_161970_127969_161770_160102_161958_160897_161729_162347_131423_160861_128698_161082_153149_162445_158055_160800_162169_161965_159954_160422_162474_162151_144966_162095_162187_161239_139883_158640_155530_163114_147552_162479_162267_162524_162861_162816_162642_159092_162264_162261_162155_110085_162026_163321; BAIDUID=CA1D410F7713287242D266621C18831C:FG=1; __yjs_duid=1_2f71f9689f273d49d3b607ed4bead1ca1611406958065; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; H_PS_PSSID=33423_33582_33273_31253_26350_33544; delPer=0; PSINO=7; BAIDUID_BFESS=308E2AF32F2705030DB38E99B12C6328:FG=1; BDRCVFR[feWj1Vr5u3D]=mk3SLVN4HKm; BA_HECTOR=2kal01a58ga42h8gqt1g27n8q0r; st_key_id=17; Hm_lvt_98b9d8c2fd6608d564bf2ac2ae642948=1612899973,1612899985,1612963100,1612963106; ab_sr=1.0.0_OTNlZDA4ZTNjNWQzYzEyZTg3NmU3ZTU2ZTM0OTYzMzM2NWFhOTgwMThmNWU4N2Y5YWExNWExOTM2ZThmM2JmMTJlOTZmZTRhYzE2ODZiOGJjMTQ4MjEyNTJkZjY1OTZlODZiZjg2NDE4MWRiZDJmZmUxNWRmN2JiZTgzM2ZmZTA=; st_data=6ff647c25e22e6e2098ddd2b4d912445ecd2b7a96a113d85893a95c7106afea705096a5203902ba371dce271f377c6fe1cf78cee29958d81bc1b2eefaafff0eb919f7810870e1562e9e0da7fd55f383a36176d3d772d68e90ff7eb8e121e5085d76aa9b6314c23eebd55995d0777b5950d21b55485d174f84dafb08ea9375a31; st_sign=8f3d7169; baidu_broswer_setup_sargarse=0; Hm_lpvt_98b9d8c2fd6608d564bf2ac2ae642948=1612963136; BDUSS=0lQdzl0LUtwRGdvSmJILTVuaDRsRjJndG9VV25rMVFnVDA5M0JjV0JKaG9ha3RnRVFBQUFBJCQAAAAAAAAAAAEAAACuIkFKc2FyZ2Fyc2UAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGjdI2Bo3SNgZ; BDUSS_BFESS=0lQdzl0LUtwRGdvSmJILTVuaDRsRjJndG9VV25rMVFnVDA5M0JjV0JKaG9ha3RnRVFBQUFBJCQAAAAAAAAAAAEAAACuIkFKc2FyZ2Fyc2UAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGjdI2Bo3SNgZ; STOKEN=1475d1ef2d029f121173478668e6605d6dd6dbc639869b78c0e1318306d5f9af",
            'user-Agent': str(ua.user_agent),
            'content-Type': 'application/json'
        }
        url = 'https://tieba.baidu.com/tbmall/onekeySignin1'
        param = {'ie': 'utf-8', 'tbs': 'dbcb633d0a5796b81612963177'}
        a = requests.post(url, data=param, headers=headers)
        msg = MessageChain.create([
            Plain("签到成功的贴吧为" + str(a.json()['data']['signedForumAmount']) +
                  '个\n' + "签到失败的贴吧为" +
                  str(a.json()['data']['signedForumAmountFail']) + '个')
        ])
        await app.sendGroupMessage(group, msg)

    if message.asDisplay().startswith("点歌"):
        await song(app, inc, group, member, message.asDisplay())

    # if member.id == 5980403 and message.asDisplay().startswith("订阅直播 "):
    #     room_id = message.asDisplay().replace("订阅直播 ",'')
    #     global info

    #     Localpath = 'data/data.json'
    #     data = {}
    #     fr = open(Localpath,encoding = 'utf-8')
    #     data = json.load(fr)
    #     fr.close

    #     for i in data['data']:
    #         if room_id == str(i['room_id']):
    #             if group.id in i['group']:
    #                 await app.sendGroupMessage(group,MessageChain.create([Plain("这个直播已经在订阅列表中了哦~")]))
    #                 break

    #         else:
    #             try:
    #                 if not room_id in info:
    #                     info['room_id'] = asyncio.create_task(entrance(app,room_id))
    #                 info = get_info(room_id)
    #                 await app.sendGroupMessage(group, MessageChain.create([Plain("开启对%s(%d)的直播间订阅" % (info['user'], info['uid']))]))
    #                 livewrite(group.id, int(room_id))
    #             except:
    #                 await app.sendGroupMessage(group, MessageChain.create([Plain("开启直播订阅失败,请检查房间号")]))
    #                 del info['room_id']

    if message.asDisplay() == "直播help":
        help_str = "目前红群直播的开启功能已经基本上由凛夜哥哥写完了,下面是大概的使用方法~\n"
        help_str += "首先,直播开启的权限是由白名单决定的,白名单存储在服务器上,只能由红群和tfcc群的管理员以及凛夜本人进行添加。添加方法为:【白名单添加 qq号】。管理员必须要注意的是:添加完qq号以后,请马上输入【添加id 名字】来添加qq号成员对应的名字,不然白名单可能会无法正常运行!\n"
        help_str += "然后开启直播的方法是【开始直播】。只有白名单上的成员才能开启直播哦!如果你想查看白名单的成员,请输入【直播白名单】,或者是之前莉莉白的查看方式【!白名单】。这里凛夜哥哥是为了迎合大家之前的习惯做的~\n"
        help_str += "如果需要修改白名单,请发送【白名单删除 qq号】。请管理员注意,删除完白名单上的qq号以后请务必删除qq号对应的id!方法为【删除id 名字】!\n"
        help_str += "如果有人在开启直播,其他白名单上的成员还发送了【开始直播】,那么机器人会提醒你有人在使用直播~如果使用直播的人需要下线,请发送【关闭直播】。而且关闭直播的权限只有开启直播的本人有哦~\n"
        help_str += "在进行tfcc比赛时可能会需要随时更改直播标题,请发送【修改直播标题 目标名字】即可~"
        await app.sendGroupMessage(group,
                                   MessageChain.create([Plain(help_str)]))

    if message.asDisplay().startswith("白名单添加 "):
        memper = member.permission
        memper = str(memper)
        if (group.id == 182721157 or group.id == 1158449372
                or group.id == 431987102 or group.id
                == 909918392) and (memper == "MemberPerm.Owner"
                                   or memper == "MemberPerm.Administrator"
                                   or member.id == 5980403):
            identification = message.asDisplay().replace("白名单添加 ", '')
            with open("./data/authority.txt", 'r+') as autho:
                exist_IDs = autho.readlines()
                for i in range(len(exist_IDs)):
                    exist_IDs[i] = exist_IDs[i].replace('\n', '')
                    if identification == exist_IDs[i]:
                        await app.sendGroupMessage(
                            group,
                            MessageChain.create([Plain("白名单上已经有该成员了!")]))
                        return
                autho.write(identification)
                autho.write('\n')
                autho.close()
            await app.sendGroupMessage(
                group, MessageChain.create([Plain("白名单添加成功!")]))

    if message.asDisplay().startswith("添加id "):
        memper = member.permission
        memper = str(memper)
        if (group.id == 182721157 or group.id == 1158449372
                or group.id == 431987102 or group.id
                == 909918392) and (memper == "MemberPerm.Owner"
                                   or memper == "MemberPerm.Administrator"
                                   or member.id == 5980403):
            with open("./data/authoid.txt", 'a') as temp_name:
                temp_identification = message.asDisplay().replace("添加id ", '')
                print(temp_identification)
                temp_name.write(temp_identification)
                temp_name.write('\n')
                temp_name.close()
            await app.sendGroupMessage(
                group, MessageChain.create([Plain("白名单id添加成功!")]))

    if message.asDisplay().startswith("白名单删除 "):
        memper = member.permission
        memper = str(memper)
        if (group.id == 182721157 or group.id == 1158449372
                or group.id == 431987102 or group.id
                == 909918392) and (memper == "MemberPerm.Owner"
                                   or memper == "MemberPerm.Administrator"
                                   or member.id == 5980403):
            identificate = message.asDisplay().replace("白名单删除 ", '')
            target_IDs = ['0']
            with open("./data/authority.txt", 'r+', encoding='utf-8') as aut:
                target_IDs = aut.readlines()
                where_flag = 0
                for i in range(len(target_IDs)):
                    if identificate == target_IDs[i].replace('\n', ''):
                        target_IDs.pop(i)
                        where_flag = 1
                        break
                aut.close()
            if where_flag == 0:
                await app.sendGroupMessage(
                    group, MessageChain.create([Plain("白名单上没有该成员~")]))
            else:
                with open("./data/authority.txt", 'w',
                          encoding='utf-8') as real_aut:
                    real_aut_content = ""
                    for i in range(len(target_IDs)):
                        real_aut_content += target_IDs[i]
                    real_aut.write(real_aut_content)
                    real_aut.close()
                await app.sendGroupMessage(
                    group, MessageChain.create([Plain("删除成功!")]))

    if message.asDisplay().startswith("删除id "):
        memper = member.permission
        memper = str(memper)
        if (group.id == 182721157 or group.id == 1158449372
                or group.id == 431987102 or group.id
                == 909918392) and (memper == "MemberPerm.Owner"
                                   or memper == "MemberPerm.Administrator"
                                   or member.id == 5980403):
            identificate_name = message.asDisplay().replace("删除id ", '')
            target_name = ['0']
            with open("./data/authoid.txt", 'r+', encoding='utf-8') as nam:
                target_name = nam.readlines()
                which_flag = 0
                for i in range(len(target_name)):
                    if identificate_name == target_name[i].replace('\n', ''):
                        target_name.pop(i)
                        which_flag = 1
                        break
                nam.close()
            if which_flag == 0:
                await app.sendGroupMessage(
                    group, MessageChain.create([Plain("你删除了错误的id!")]))
            else:
                with open("./data/authoid.txt", 'w',
                          encoding='utf-8') as real_nam:
                    real_nam_content = ""
                    for i in range(len(target_name)):
                        real_nam_content += target_name[i]
                    real_nam.write(real_nam_content)
                    real_nam.close()
                await app.sendGroupMessage(
                    group, MessageChain.create([Plain("id删除成功!")]))

    if message.asDisplay().startswith("角色曲 "):
        character = message.asDisplay().replace('角色曲 ', '')
        with open("./data/touhou.json",
                  encoding='utf-8') as touhou_characters_file:
            touhou_characters = json.load(touhou_characters_file)
            try:
                touhou_music = touhou_characters[character]
                touhou_characters_file.close()
            except:
                await app.sendGroupMessage(
                    group, MessageChain.create([Plain("没有该角色曲!")]))
                touhou_characters_file.close()
                return
        music_file = './voice/' + touhou_music + '.silk'
        print(music_file)
        await app.sendGroupMessage(
            group,
            MessageChain.create(
                [Voice.fromLocalFile(0, filepath=Path(music_file))]))

    if (message.asDisplay() == "!白名单" or message.asDisplay() == "查看白名单") and (
            group.id == 182721157 or group.id == 1158449372
            or group.id == 431987102 or group.id == 909918392):
        IDs = ['0']
        msg_str = "白名单如下:\n"
        with open("./data/authority.txt", encoding='utf-8') as auth:
            with open("./data/authoid.txt", encoding='utf-8') as authname:
                IDs = auth.readlines()
                Names = authname.readlines()
                for i in range(len(IDs)):
                    msg_str = msg_str + Names[i].replace(
                        '\n', '') + "(" + IDs[i].replace('\n', '') + ")"
                    if i < len(IDs) - 1:
                        msg_str += '\n'
        await app.sendGroupMessage(group,
                                   MessageChain.create([Plain(msg_str)]))

    if message.asDisplay() == "开始直播" or message.asDisplay(
    ) == "关闭直播" or message.asDisplay().startswith("修改直播标题"):
        IDs = ['0']
        with open("./data/authority.txt", encoding='utf-8') as auth:
            IDs = auth.readlines()
            for i in range(len(IDs)):
                IDs[i] = IDs[i].replace('\n', '')

        if not str(member.id) in IDs:
            await app.sendGroupMessage(
                group,
                MessageChain.create(
                    [At(member.id),
                     Plain("  你无权开启直播,请向管理员申请添加白名单^-^")]))
            return
        else:
            if message.asDisplay() == "开始直播":
                Localpath = './data/live.json'
                live_info = {}
                fr = open(Localpath, encoding='utf-8')
                live_info = json.load(fr)
                fr.close()
                if live_info['live_status'] == 1:
                    await app.sendGroupMessage(
                        group,
                        MessageChain.create([
                            At(member.id),
                            Plain("  已经有人在使用直播间了"),
                            Face(faceId=111)
                        ]))
                    return
                else:
                    live_info['member_id'] = member.id
                    live_info['group_id'] = group.id
                    live_info['live_status'] = 1
                    with open(Localpath, "w") as fw:
                        jsObj = json.dumps(live_info)
                        fw.write(jsObj)
                        fw.close()
                    await getlive(app, group, member)

            if message.asDisplay() == "关闭直播" or message.asDisplay() == "停止直播":
                Localpath = './data/live.json'
                live_info = {}
                fr = open(Localpath, encoding='utf-8')
                live_info = json.load(fr)
                fr.close()
                if live_info['member_id'] != member.id or live_info[
                        'group_id'] != group.id:
                    await app.sendGroupMessage(
                        group,
                        MessageChain.create([
                            At(member.id),
                            Plain("  你无权关闭直播"),
                            Face(faceId=111)
                        ]))
                    return
                elif live_info['live_status'] == 0:
                    await app.sendGroupMessage(
                        group,
                        MessageChain.create([
                            At(member.id),
                            Plain("  直播间现在是关闭状态哦~请发送'开始直播'来申请直播!")
                        ]))
                else:
                    live_info['live_status'] = 0
                    with open(Localpath, "w") as fw:
                        jsObj = json.dumps(live_info)
                        fw.write(jsObj)
                        fw.close()
                    await liveend(app, group)

            if message.asDisplay().startswith("修改直播标题"):
                await livechange(app, group, message.asDisplay())
コード例 #25
0
async def group_message_handler(app: GraiaMiraiApplication, message: MessageChain, group: Group, member: Member):
    tmsg = ""
    timg = ""
    tat = 0
    id = str(member.id)
    if int(id) in cfg['ban']:
        return
    if message.has((Plain)):tmsg = str(message.get((Plain))[0].text)
    tsource = int(str(message.get((Source))[0].id))
    file_count = x = 0
    msg = message.asDisplay()
#@聊天图片检测
    if message.has((Image)):
        timg = str(message.get(Image)[0].url)
        print(timg)
        file_path = './chace/' + str(group.id) + ".jpg"
        d = file_path
        urlretrieve(timg, d)
        img1=cv2.imread(file_path)
        hash1= dHash(img1)
        n=cmpHash(hash1,hash2)
        if n == 0 :
            csh(id)
            outmsg="未知错误"
            gr = group.id
            mb = member.id
            outmsg = setu(gr,mb)
            st = cfg['hsolvch']
            botmsg = await app.sendGroupMessage(group,MessageChain.create(outmsg))
            await asyncio.sleep(int(st))
            await app.revokeMessage(botmsg)
        if message.has((At)):
            tat = int(str(message.get((At))[0].target))
            if tat == bot_qq:
#@以图搜图
                print('以图搜图')
                url = "https://saucenao.com/search.php?output_type=2&api_key=$key&testmode=1&dbmask=999&numres=1&url=$url".replace('$url',timg).replace('$key',apikey)
                headers = {}
                text = requests.get(url, headers=headers) 
                data = json.loads(text.text)
                datadata = data['results'][0]["data"]
                n = 0
                outmsg = ""
                print('done')
                uid = "justsetu"
                for i in datadata:
                    outmsg = outmsg + '\n' + str(i) + ":" + str(datadata[i])
                if outmsg.find('urls:[\'https://www.pixiv') >= 1:
                    pid = str(datadata['pixiv_id'])
                    uid = str(data['results'][0]['data']['member_id'])
                    cfg['setuadd'] = pid
                    dstfile=setu_ + uid + '/' +  pid + "_p0.jpg"
                    sdir(setu_+ '/' + uid)
                tmsg = tmsg.replace(' ','')
                print(tmsg)
                if msg.find('setu+') >=1 and member.id in op:
                    print('setu+')
                    tmsg = tmsg.replace('setu+','')
                    pid = cfg['setuadd']
                    print(1)
                    srcfile= './chace/' + str(group.id) + ".jpg"
                    dstfile=setu_ + '/' + uid + '/' +  pid + "_p0.jpg"
                    print(dstfile)
                    shutil.move(srcfile,dstfile)
                    print(2)
                    outmsg = 'pid:' + pid + 'by' + uid + '\n已被从qq下载图片并加入色图库'
                await app.sendGroupMessage(group,MessageChain.create([Plain(outmsg)]))
#@机器人
    elif message.has((At)):
        tat = int(str(message.get((At))[0].target))
        if tat == bot_qq:
            newdata = {}
            n = 0
            for i in feback_data:
                n = n + 1
                newdata[str(n)] = i
            csh(id)
            hsolv = stlist_data[id]
            if hsolv >= 60:
                r1 = 20
                r2 = 96
                r3 = 101
            elif member.id in admin:
                r1 = 10
                r2 = 30
                r3 = 100
            else:
                r1 = 100
                r2 = 101
                r3 = 102
            r = random.randint(1,100)
            if r <= r1:
                data = newdata['1']
            elif r <= r2:
                data = newdata['2']
            elif r <= r3:
                data = newdata['3']
            else:
                print('几率设置错误')
                data = newdata['1']
            tmsg = tmsg.replace(' ','')
            print(tmsg)
            for i in data:
                if tmsg.startswith(i):
                    outmsg = 'truemsg in data'
                    text = data[tmsg]
                    arr = text.split('|')
                    max = len(arr) - 1
                    r = random.randint(0,max)
                    outmsg = str(arr[r])
                    await app.sendGroupMessage(group,MessageChain.create([Plain(outmsg)]))
#早
    if msg.startswith('早') and member.id in admin:
        outmsg = '啊啊啊,主人睡傻了QAQ'
        await app.sendGroupMessage(group,MessageChain.create([Plain(outmsg)]))
#setu+
    elif msg.startswith('setu+') and member.id in admin:
        pid = int(cfg['setuadd'])
        if msg.startswith('setu+ '):
            msg = msg.replace('setu+','').replace(' ','')
        print(msg)
        if msg.startswith('sf'):
            msg=msg.replace('sf','')
            pid = int(msg)
            pach = './chace/' + str(group.id) + ".jpg"
            srcfile=pach
            dstfile=setu_ + 'justsetu' + '/' +  str(pid) + "_p0.jpg"
            shutil.move(srcfile,dstfile)
            await app.sendGroupMessage(group,MessageChain.create([Plain(str(pid) + '已从缓存下载并加入色图库')]))
        else:
            pid = int(msg.replace('p0','').replace('p1','').replace('p2','').replace('p3',''))
            print(pid)
            url = 'https://api.imjad.cn/pixiv/v2/?type=illust&id=$id'.replace('$id',str(pid))
            headers = {}
            text = requests.get(url, headers=headers)
            print('getdone')
            data = json.loads(text.text)
            data = data['illust']
            userid = str(data['user']['id'])
            data1 = data['meta_pages']
            _p = 'p0'
            if data1 == []:
                print('null')
                data1 = data['meta_single_page']
                data = data1['original_image_url']
            else:
                data1 = data['meta_pages']
                data = data1[0]["image_urls"]["original"]
                if msg.find('p1') >=1:
                    data = data1[1]["image_urls"]["original"]
                    _p = 'p1'
                if msg.find('p2') >=1:
                    data = data1[2]["image_urls"]["original"]
                    _p = 'p2'
                if msg.find('p3') >=1:
                    data = data1[3]["image_urls"]["original"]
                    _p = 'p3'
            print(data)
            if data.find('png') >=1:
                srcfile='./' + str(pid) + "_p0.png".replace('p0',_p)
                dstfile=setu_ + "/"  + userid + '/' + str(pid) + "_p0.png".replace('p0',_p)
            else:
                srcfile='./' + str(pid) + "_p0.jpg".replace('p0',_p)
                dstfile=setu_ + "/" + userid + '/' +  str(pid) + "_p0.jpg".replace('p0',_p)
            print(srcfile,dstfile)
            my_file = Path(dstfile)
            print(pid,'下载中')
            if my_file.is_file() == False:
                sdir(setu_ + '/' + userid)
                print('开始下载',data)
                api.download(data)
                print('下载完成')
                shutil.move(srcfile,dstfile)
                await app.sendGroupMessage(group,MessageChain.create([Plain(str(pid) + '已加入色图库')]))
            else:
                print('略过')
                await app.sendGroupMessage(group,MessageChain.create([Plain(dstfile + '已存在')]))
#菜单
    elif msg.startswith("/help") or msg.startswith('菜单') or msg.startswith('main'):
        print("main")
        ism = 1
        fontl = f1
        fonty = f2
        img = "./chace/mainbg.png"
        msg = mainmap
        cm = 0
        toimg(msg,fontl,fonty,ism,img,cm)
        await app.sendGroupMessage(group,MessageChain.create([Image.fromLocalFile("./chace/1.png")]))
#帮助
    elif msg.startswith('h ') or msg.startswith('/h'):
        msg = msg.replace('h ','').replace('/','')
        ism = 0
        cm = 0
        print('帮助')
        img = "./chace/mainbg.png"
        ism = 1
        if msg.startswith('hsolv'):
            msg = hsolvtext
            toimg(msg,f1,f2,ism,img,cm)
        elif msg.startswith('扫雷'):
            msg = sl
            toimg(msg,f1,f2,ism,img,cm)
        elif msg.startswith('img'):
            msg = imgh
            toimg(msg,f1,f2,ism,img,cm)
        elif msg.startswith('短链'):
            msg = dlmsg
            toimg(msg,f1,f2,ism,img,cm)
        elif msg.startswith('热榜'):
            msg = rb
            toimg(msg,f1,f2,ism,img,cm)
        if ism == 1:
            await app.sendGroupMessage(group,MessageChain.create([Image.fromLocalFile("./chace/1.png")]))
        else:
            await app.sendGroupMessage(group,MessageChain.create([Plain('帮助文本不存在')]))
#汇报不够色 - rep
    elif msg.startswith("rep"):
        gr = str(group.id)
        msg = msg.replace('rep','')
        hsolv = stlist_data[id]
        if msg.startswith('- ') and member.id in op:
            msg = msg.replace('- ','')
            dstfile=setu_ +'/' + msg.replace('-','/')
            srcfile=setu_remove_ +'/' + msg
            print(srcfile,'to',dstfile,':',gr + '-' + str(member.id))
            shutil.move(srcfile,dstfile)
            outmsg = msg.replace('-','/') + "已恢复"
        elif hsolv >= 80 or member.id in op:
            name = str(lstgr_data[gr])
            srcfile=setu_ +'/' + name
            dstfile=setu_remove_ +'/' + name.replace('/','-')
            print(srcfile,'to',dstfile,':',gr + '-' + str(member.id))
            shutil.move(srcfile,dstfile)
            outmsg = name + "已汇报且暂时移出色图库"
        else:outmsg = "你没有权限执行此操作"
        await app.sendGroupMessage(group,MessageChain.create([Plain(outmsg)]))
#撤回时间
    elif msg.startswith("hsolvch") and member.id in admin != 0:
        thetext = msg.replace("hsolvch ","")
        cfg['hsolvch'] = int(thetext)
        outmsg = "撤回时间已改为" + thetext + "秒"
        await app.sendGroupMessage(group,MessageChain.create([Plain(outmsg)]))
#色图群权限
    elif msg.startswith("sg") and member.id in admin != 0:
        setugroup = message.asDisplay().replace('sg','')
        outmsg = "发生未知错误"
        theg = setugroup.replace('-','').replace('+','').replace(' ','')
        if theg.isdigit():
            theg = theg
        else:
            theg = str(group.id)
        if int(theg) in cfg['sg']:
            if setugroup.startswith('-'):
                p = cfg['sg'].index(int(theg))
                del cfg['sg'][p]
                outmsg = "已禁用此群的色图权限"
            else:
                outmsg = "此群已是色图群"
        else:
            if setugroup.startswith('-'):
                outmsg = "此群不存在"
            else:
                new = int(theg)
                cfg['sg'].append(new)
                outmsg = "已将此群变更为色图群"
        await app.sendGroupMessage(group,MessageChain.create([Plain(outmsg)]))
#ban
    elif msg.startswith("ban") and member.id in admin != 0 :
        
        msg = msg.replace('ban','').replace(' ','')
        if msg.startswith('-'):
            msg = msg.replace('-','')
            cfg['ban'].remove(int(msg))
            outmsg = msg + "ban-"
        else:
            if int(msg) in cfg['ban'] != 0:
                outmsg = "已存在"
            else:
                cfg['ban'].append(int(msg))
                outmsg = msg + "ban+"
        await app.sendGroupMessage(group,MessageChain.create([Plain(outmsg)]))
#hsolvmax 色图限制
    elif msg.startswith("hsolvmax") and member.id in admin != 0 :
        thetext = msg.replace("hsolvmax ","")
        cfg['hsolvmax'] = int(thetext)
        outmsg = "色图限制上限已被改为" + thetext
        await app.sendGroupMessage(group,MessageChain.create([Plain(outmsg)]))
#hso等级清零
    elif msg.startswith("hsolv") and member.id in admin:
        msg = msg.replace("hsolv",'')
        if msg.startswith('- *'):
            outmsg = "所有当天hso等级被清除"
            for i in id_data:
                id_data[i] = 0
            for i in qdlist_data:
                qd_data[i] = 0
            await app.sendGroupMessage(group,MessageChain.create([Plain(outmsg)]))
            savecfg()
            srcfile='./cfg.json'
            name = time.strftime('%Y-%m-%d-%H',time.localtime(time.time()))
            dstfile='./backups/'+ name + '.json'
            shutil.move(srcfile,dstfile)
        elif msg.startswith('-'):
            id = int(msg.replace("-","").replace(' ',''))
            id_data[id] = 0
            outmsg = str(id) + "的hso等级已降到0"
            await app.sendGroupMessage(group,MessageChain.create([Plain(outmsg)]))
            savecfg()
#lsp排行榜
        elif msg.startswith('list'):
            print("list读取")
            groupids = []
            hsolvlist = []
            n = 0
            mlist = await app.memberList(group)
            for i in mlist:
                groupids.append(i.id)
            for item in stlist_data:
                if int(item) in groupids != 0:
                    for i in mlist:
                        if i.id == int(item) != 0:
                            itemid = await app.getMember(group,int(item))
                            inmsg = '|$item:$int'.replace('$item',itemid.name).replace('$int',str(stlist_data[item]))
                            hsolvlist.append(str(inmsg))
            res = sorted(hsolvlist, key=lambda x: (lambda y: (int(y[1]), y[0]))(x.split(':')))
            res.reverse()
            out = ''
            for i in res:
                if n == 0:
                    for i in res[n]:
                        r = random.randint(0,18)
                        out = out + '#' + hsomap[r] + ''.join(i)
                    res[n] = '\\b30##FF0000' + out
                if n == 1:
                    res[n] = '\\b25##FF0000' + res[n]
                if n == 3:
                    res[n] = '\\b20##FF3300'+ res[n]
                if n == 6:
                    res[n] = '##FF6600'+ res[n]
                if n == 9:
                    res[n] = '##FF9900'+ res[n]
                if n == 12:
                    res[n] = '##FFCC00'+ res[n]
                if n == 15:
                    res[n] = '##FFFF00'+ res[n]
                if n == 18:
                    res[n] = '##FFFF66'+ res[n]
                if n == 21:
                    res[n] = '##FFFFCC'+ res[n]
                if n == 24:
                    res[n] = '##FFFFFF'+ res[n]
                n = n + 1
            a = '‘'.join(res)
            msg = "-lsp排行榜:‘\\b20" + a + "‘    ‘______________________"
            fontl = f1
            fonty = f2
            ism = 1
            cm = 0
            img = "./chace/mainbg.png"
            toimg(msg,fontl,fonty,ism,img,cm)
            await app.sendGroupMessage(group,MessageChain.create([Image.fromLocalFile("./chace/1.png")]))
        else:
            print("printhsolv")
            id = int(msg.replace("-","").replace(' ',''))
            mid = 0
            mid = int(stlist_data[str(id)])
            outmsg = str(id) + "的hso等级为" + str(mid)
            await app.sendGroupMessage(group,MessageChain.create([Plain(outmsg)]))
    elif msg.startswith('backup') and member.id in admin:
        savecfg()
        srcfile='./cfg.json'
        name = time.strftime('%Y-%m-%d-%H',time.localtime(time.time()))
        dstfile='./backups/'+ name + '.json'
        shutil.move(srcfile,dstfile)
        outmsg = name + '已备份'
        await app.sendGroupMessage(group,MessageChain.create([Plain(outmsg)]))
#签到
    elif msg.startswith('签到'):
        stadd = random.randint(5,20)
        outmsg = "签到成功\n群聊色图限制已重置\n随机获得了色图$张"
        datas = [id_data,fr_data,stlist_data,qdlist_data,qd_data]
        u = 0
        for i in datas :
            if id not in i:
                i[id] = 0
                u = u + 1
        if u >= 1: 
            print(id + ':配置初始化完成')
            stadd = stadd + 10
            outmsg = outmsg + "\n使用来份色图获取色图,群内要色图只会发链接(色图群会优先消耗hsolv*),私聊会发图\n这是你第一次签到"
        if qd_data[id] == 0:
            qd_data[id] = 1
            qdlist_data[id] = qdlist_data[id] + 1
            id_data[id] = 0
            fr_data[id] = fr_data[id] + stadd
            outmsg = outmsg.replace('$',str(stadd))
        else:
            outmsg="你今天已经签到过了"
        await app.sendGroupMessage(group,MessageChain.create([Plain(outmsg)]))
#img
    elif msg.startswith("img"):
        cm = 0
        if msg.find('!main') >= 1:
            ism = 1
            img = "./chace/mainbg.png"
            msg = msg.replace('!main','')
        elif msg.find('!cimg') >=1:
            ism = 1
            msg = msg.replace('!cimg','').replace('[图片','')
            msg = msg[0:msg.rfind('text=')].replace("/r",'')
            cm = 1
            img = './chace/' + str(group.id) + ".jpg"
        elif msg.find('!xm') >=1:
            ism = 1
            msg = msg.replace('!xm','')
            msg = msg[0:msg.rfind('text=')].replace("/r",'')
            cm = 1
            img = './chace/xm.jpg'
        else:
            ism = 0
            img = ""
        fontl = f1
        fonty = f2
        msg = msg.replace('img ','')
        toimg(msg,fontl,fonty,ism,img,cm)
        await app.sendGroupMessage(group,MessageChain.create([Image.fromLocalFile("./chace/1.png")]))
#ping
    elif msg.startswith("ping "):
        ip = message.asDisplay().replace('ping ',"")
        url = "http://weijieyue.cn/api/ping.php?ip=$ip".replace('$ip',ip)
        header = {}
        r = requests.get(url, headers=header)
        await app.sendGroupMessage(group,MessageChain.create([Plain(r.text)]))
#舔狗日记
    elif msg.startswith("舔狗日记"):
        cm = 0
        print('请求舔狗日记...')
        url = "http://www.dashige.xyz/API/tgrj/api.php"
        header = {}
        text = requests.get(url, headers=header) 
        msg ="##FFFFFF- "  + text.text + ""
        getimg()
        l = f1
        y = f2
        ism = 1
        img = "./chace/imgchace.jpg"
        toimg(msg,l,y,ism,img,cm)
        await app.sendGroupMessage(group,MessageChain.create([Image.fromLocalFile("./chace/1.png")]))
#run
    elif msg.startswith('run -getimg') and member.id in admin:
        getimg()
#历史上的今天
    elif msg.startswith('历史'):
        cm = 0
        print('请求历史上的今天...')
        url = "http://kumeng.ihcblog.cn/api/today.php"
        header = {}
        text = requests.get(url, headers=header) 
        text = "历史上的今天:" + text.text.replace('1:','$').replace('2:','$').replace('3:','$').replace('4:','$').replace('5:','$').replace('6:','$').replace('7:','$').replace('8:','$').replace('9:','$').replace('注意:由内容过长,只显示10个列','')
        alist = text.split('$')
        msg = '‘'.join(alist)
        l = f1
        y = f2
        ism = 1
        getimg()
        img = "./chace/imgchace.jpg"
        print('调用def...')
        toimg(msg,l,y,ism,img,cm)
        await app.sendGroupMessage(group,MessageChain.create([Image.fromLocalFile("./chace/1.png")]))
#网抑云
    elif msg.startswith('网抑云'):
        cm = 0
        print('请求网抑云api...')
        url =  'https://nd.2890.ltd/api/'
        headers = {}
        text = requests.get(url, headers=headers)
        print(1)
        if text.text.find('520: 源站返回未知错误') >=1:
            outmsg='错误:520'
        else:
            print(text.text)
            data = json.loads(text.text)
            data = data['data']
            data = data['content']
            outmsg = str(data['content'])
        await app.sendGroupMessage(group,MessageChain.create([Plain(outmsg)]))
#群直链
    elif msg.startswith('群直链'):
        msg = msg.replace('群直链','')
        if msg.startswith(' '):
            msg = msg.replace(' ','')
            qun = msg
        else:
            qun = str(group.id)
        url =  'https://v1.alapi.cn/api/qun?Token=DQLznnjagptUuvzN9rsC&format=json&guin=$id'.replace('$id',qun)
        headers = {'Content-Type': "application/x-www-form-urlencoded"}
        text = requests.request("POST", url, data=url, headers=headers)
        data = json.loads(text.text)
        if data["code"] != 200:
            outmsg = "发生错误" + str(data["msg"])
        else :
            datain = data['data']
            qunid = str(datain['guin'])
            outurl = str(datain['url'])
            outmsg = '群号:$i\n链接:$u'.replace('$i',qunid).replace('$u',outurl)
        await app.sendGroupMessage(group,MessageChain.create([Plain(outmsg)]))
#直链
    elif msg.startswith('直链'):
        msg = msg.replace('直链 ','')
        if msg.startswith('www'):
           msg = msg.replace('www','https://www')
        if msg.find('lanzous') >= 1:
            print('蓝奏云解析')
            if msg.find('密码') >= 1:
                mm = msg[msg.rfind('密码'):].replace('密码')
                msg = msg[0:msg.rfind('密码')] 
                url = "https://v1.alapi.cn/api/lanzou?Token=DQLznnjagptUuvzN9rsC&url=$h&format=&$f&$m".replace('$h',msg).replace('$f','json').replace('$m',"pwd=" + mm)
            else:
                url = "https://v1.alapi.cn/api/lanzou?Token=DQLznnjagptUuvzN9rsC&url=$h&format=$f".replace('$h',msg).replace('$f','json')
            headers = {'Content-Type': "application/x-www-form-urlencoded"}
            text = requests.request("POST", url, data=url, headers=headers)
            data = json.loads(text.text)
            if data["code"] != 200:
                outmsg = "发生错误" + str(data["msg"])
            else :
                datain = data['data']
                outurl = str(datain['url'])
                outmsg = 'u$u'.replace('$u',outurl)
        else:
            outmsg = '不支持的直链网站或其他错误'
        await app.sendGroupMessage(group,MessageChain.create([Plain(outmsg)]))
#短链 1 xxxxxx
    elif msg.startswith('短链 '):
        tt = 1
        uf = ' '
        print('短链' + msg)
        msg = msg.replace('短链 ','')
        for i in thetypes:
            uf = str(i) + " "
            if msg.startswith(uf):
                msg = msg.replace(uf,'')
                tt = uf.replace(' ','')
        msg = msg.replace(uf,'').replace(' ','')
        print('type=',str(tt))
        url = "https://v1.alapi.cn/api/url?url=$u&Token=DQLznnjagptUuvzN9rsC&type=$tt".replace('$tt',str(tt)).replace('$u',msg)
        print(url)
        headers = {'Content-Type': "application/x-www-form-urlencoded"}
        response = requests.request("POST", url, headers=headers)
        print('请求完成')
        outmsg = "发生未知错误"
        data = json.loads(response.text)
        if data["code"] != 200:
            outmsg = "发生错误" + str(data["msg"])
        else :
            datain = data['data']
            outurl = str(datain['short_url'])
            outmsg = str(outurl)
        await app.sendGroupMessage(group,MessageChain.create([Plain(outmsg)]))
#热榜
    elif msg.startswith('热榜'):
        qaq = False
        t = "bilibili"
        outmsg = "发生未知错误"
        msg = msg.replace('热榜','').replace(' ','')
        if msg.startswith('p'):
            csh(id)
            if fr_data[id] >= 3:
                await app.sendGroupMessage(group,MessageChain.create([Plain('你消耗了3个色图进行搜索....')]))
                url = 'https://api.imjad.cn/pixiv/v2/?type=rank'
                msglist = papi(url)
                st = cfg['hsolvch']
                botmsg = await app.sendGroupMessage(group,MessageChain.create(msglist))
                fr_data[id] = fr_data[id] - 3
                savecfg()
                if int(st) > 0:
                    st = int(st)
                    st = st * 8
                    await asyncio.sleep(st)
                    await app.revokeMessage(botmsg)
            else:await app.sendGroupMessage(group,MessageChain.create([Plain('你的剩余色图不足3')]))
        else:
            for i in resotypes:
                if msg.startswith(i):
                    t = i
                    msg = msg.replace(i,'')
    
            print(t)
            print(msg)
            for i in listtype:
                if msg.startswith(i):
                    qaq = True
                    ta = int(msg)
                    n = 0
                    data = rel_data['data']
                    listdata = data['list']
                    for i in listdata:
                        n = n + 1
                        if ta == n:
                            outmsg = str(i["link"])
                    print(2)
                    await app.sendGroupMessage(group,MessageChain.create([Plain(outmsg)]))
            if qaq == False:
                print('type=',t)
                url = "https://v1.alapi.cn/api/tophub/get?type=$t".replace('$t',t)
                print(url)
                headers = {'Content-Type': "application/x-www-form-urlencoded"}
                response = requests.request("POST", url, headers=headers)
                print('请求完成')
                data = json.loads(response.text)
                if data["code"] != 200:
                    outmsg = "发生错误" + str(data["msg"])
                else :
                    data1 = data['data']
                    listname = str(data1['name'])
                    lastupdate = str(data1['last_update'])
                    listdata = data1['list']
                    imgmsg = listname + '     最后更新时间:' + lastupdate 
                    n = 0
                    for i in listdata:
                        n = n + 1
                        if n >= 21:
                            break
                        title = str(i['title'])
                        rd = str(i["other"])
                        imgmsg =  imgmsg + '\\n' + str(n) + "_" + rd + "_"  + title 
                    l = f1
                    y = f2
                    ism = 1
                    imgp = "./chace/mainbg.jpg"
                    cm = 0
                    imgmsg = '\\b20' + imgmsg
                    cfg['relist'] = data
                    toimg(imgmsg,l,y,ism,imgp,cm)   
                await app.sendGroupMessage(group,MessageChain.create([Image.fromLocalFile("./chace/1.png")]))   
#百科
    elif msg.startswith('百科'):
        msg = msg.replace('百科','')
        print('请求百科...')
        url = "http://beimoapi.xyz/baike/api.php/?msg=$msg".replace('$msg',msg)
        header = {}
        text = requests.get(url, headers=header) 
        text = text.text.replace('/n','/n|').replace('(','(').replace(')',')').replace('《','<').replace('》','>')
        print('下载百科图片...')
        url = text[0:text.rfind('300±')] + "300"
        url = url.replace('±img=','')
        print(url)
        file_path = './chace/baikechace.jpg'
        urlretrieve(url, file_path)
        img = cv2.imread("./chace/baikechace.jpg", -1) 
        fx = fy = 3.6
        print("缩放")
        img = cv2.resize(img, (0, 0), fx=fx, fy=fy, interpolation=cv2.INTER_CUBIC)  
        print("高斯模糊")
        img = cv2.GaussianBlur(img,(13,13),0)
        print("保存文件")
        cv2.imwrite("./chace/baikechace.jpg", img)
        cv2.waitKey(0)  
        img="./chace/baikechace.jpg"
        print('调用def...')
        l = f1
        y = f2
        ism = 1
        cm = 0
        text = '/b20' + text[text.rfind('300±'):].replace('300±','') + '/n_____________________________________________________________________________________'
        toimg(text,l,y,ism,img,cm)
        await app.sendGroupMessage(group,MessageChain.create([Image.fromLocalFile("./chace/1.png")]))
#来份色图
    elif msg.startswith("来份色图") or msg.startswith('色图来'):
        csh(id)
        outmsg="未知错误"
        gr = group.id
        mb = member.id
        outmsg = setu(gr,mb)
        st = cfg['hsolvch']
        botmsg = await app.sendGroupMessage(group,MessageChain.create(outmsg))
        await asyncio.sleep(int(st))
        await app.revokeMessage(botmsg)
#搜
    elif msg.startswith('搜'):
        csh(id)
        n = 0
        if fr_data[id] >= 3:
            if msg.find('入り')>=1:
                url = 'https://api.imjad.cn/pixiv/v2/?type=search&word=' + msg.replace('搜索','').replace('搜','')
                msglist = papi(url)
                await app.sendGroupMessage(group,MessageChain.create([Plain('你消耗了3个色图进行[指定收藏数]搜索....')]))
            else:
                msglist = [(Plain('没有搜索结果'))]
                for i in stag:
                    imsg = await app.sendGroupMessage(group,MessageChain.create([Plain(stag2[n])]))
                    url = 'https://api.imjad.cn/pixiv/v2/?type=search&word=' + msg.replace('搜索','').replace('搜','') +' ' + stag[n]
                    msglist = papi(url)
                    n = n + 1
                    if msglist != [(Plain('没有搜索结果'))]:
                        print(len(msglist))
                        await app.revokeMessage(imsg)
                        break
                    else:await app.revokeMessage(imsg)
            st = cfg['hsolvch']
            botmsg = await app.sendGroupMessage(group,MessageChain.create(msglist))
            fr_data[id] = fr_data[id] - 3
            if msglist == [(Plain('没有搜索结果'))]:
                fr_data[id] = fr_data[id] + 3
                print('backfr')
            savecfg()
            if int(st) > 0:
                st = int(st)
                st = st * 8
                await asyncio.sleep(st)
                await app.revokeMessage(botmsg)
        else:await app.sendGroupMessage(group,MessageChain.create([Plain('你的剩余色图不足3')]))
#搜 - tp
    if msg.startswith('tp'):
        msg = msg.replace('tp','').replace(' ','')
        setid = int(msg)
        print('选择tp',setid)
        data = cfg['slist'][setid]
        pid = data['id']
        title = data['title']
        user = data['user']['name']
        tags = data['tags']
        tag = ''
        print(1)
        for i in tags:
            tag = tag + '|' + i['name']
        print(tag)
        ptime = data['create_date']
        try:
            imgurl = data['meta_single_page']['original_image_url']
        except Exception:
            imgurl = data['meta_pages'][0]['image_urls']['original']
        await app.sendGroupMessage(group,MessageChain.create([Plain('原图下载中..')]))
        api.download(imgurl)
        print('下载完成')
        if imgurl.find('png') >=1:
            srcfile='./' + str(pid) + "_p0.png"
            dstfile='./chace/s/tp.png'
        else:
            srcfile='./' + str(pid) + "_p0.jpg"
            dstfile='./chace/s/tp.jpg'
        shutil.move(srcfile,dstfile)
        outmsg1 = "id:" + str(pid) + '|标题:' + title + '|by - ' + user
        outmsg2 = 'tags:' + tag + '\n创建时间:' + ptime
        if tag.find('18') >=1:
            print(tag)
            await app.sendGroupMessage(group,MessageChain.create([Plain('r18图不支持tp')]))
        else:
            st = cfg['hsolvch']
            botmsg = await app.sendGroupMessage(group,MessageChain.create([Plain(outmsg1),Image.fromLocalFile(dstfile),Plain(outmsg2)]))
            if int(st) > 0:
                st = int(st) * 3
                await asyncio.sleep(st)
                await app.revokeMessage(botmsg)
#不够色
    elif msg.startswith('不够色'):
        await app.sendGroupMessage(group,MessageChain.create([Plain('那你发')]))
#统计色图-
    elif msg.startswith("统计色图"):
        rootdir = setu_
        for dirpath, dirnames, filenames in os.walk(rootdir):
            for file in filenames:
                file_count = file_count + 1
            print(dirpath,file_count)
        msg = "共有$sl张色图".replace("$sl",str(file_count))
        await app.sendGroupMessage(group,MessageChain.create([Plain(msg)]))
#后执行项目
    print(msg)
    savecfg()
    initDate = datetime.strptime(cfg['time'],'%Y-%m-%d %H:%M:%S')
    timedata = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    timedata2 = datetime.strptime(timedata,'%Y-%m-%d %H:%M:%S')
    firstDay = datetime(initDate.year,initDate.month,initDate.day)
    endDay = datetime(timedata2.year,timedata2.month,timedata2.day)
    days = rrule.rrule(freq = rrule.DAILY,dtstart=firstDay,until=endDay)
    if days.count() >= 2:
        await app.sendGroupMessage(group,MessageChain.create([Plain('执行自动重启项目----')]))
        if not os.path.exists('./backups'):
            os.makedirs('./backups')
        srcfile='./cfg.json'
        name = time.strftime('%Y-%m-%d-%H',time.localtime(time.time()))
        dstfile='./backups/'+ name + '.json'
        shutil.move(srcfile,dstfile)
        timenow = datetime.now().strftime('%Y-%m-%d 10:10:10')
        cfg['time'] = timenow
        for i in id_data:
            id_data[i] = 0
        for i in qdlist_data:
            qd_data[i] = 0
        savecfg()
        restart_program()
コード例 #26
0
ファイル: Bot.py プロジェクト: Crepuscule-v/QQbot
async def group_messsage_handler(message: MessageChain,
                                 app: GraiaMiraiApplication, group: Group,
                                 member: Member):
    if message.has(Image):
        img_url_list = []
        Image_list = message.get(Image)
        print(Image_list)
        for item in Image_list:
            try:
                path = re.search(r'-([\d\w]*?)/', item.url).group(1)
                with open("img\\" + path + '.jpeg', 'wb') as file:
                    byte_content = await Image.http_to_bytes(item)
                    file.write(byte_content)
                    file.close()
            except:
                print("图片保存错误")
    if message.asDisplay().startswith("/need_confirm"):
        await app.sendGroupMessage(
            group,
            MessageChain.create(
                [At(member.id),
                 Plain("Post [/confirm] to continue")]))

        @Waiter.create_using_function([GroupMessage])
        def waiter(event: GroupMessage, waiter_group: Group,
                   waiter_member: Member, waiter_message: MessageChain):
            if all([
                    waiter_member.id == member.id, waiter_group.id == group.id,
                    waiter_message.asDisplay() == "/confirm"
            ]):
                return event

        await inc.wait(waiter)
        await app.sendGroupMessage(group,
                                   MessageChain.create([Plain("\nCompleted")]))
    elif message.asDisplay().startswith("/Menu"):
        await app.sendGroupMessage(
            group, MessageChain.create([At(member.id),
                                        Plain(Menu())]))
    elif message.asDisplay().startswith("/求图"):
        msg = message.asDisplay()
        msg = re.split(r' +', msg)
        msg_to_send = MessageChain.create([At(member.id)])
        if msg.__len__() > 3 or msg.__len__() <= 1:
            msg_to_send.plus(
                MessageChain.create(
                    [Plain("\n不要搞事情! 要遵守输入格式 : '/求图 关键词 整数[可选]', 请重新输入~")]))
            await app.sendGroupMessage(group, msg_to_send)
        elif msg.__len__() == 2:
            img_url_list = await getImage.get_normal_image(msg[1])
            msg_to_send.plus(
                MessageChain.create([
                    Plain("\n您要的图~ "),
                    Image.fromNetworkAddress(img_url_list[0])
                ]))
            await app.sendGroupMessage(group, msg_to_send)
        else:
            if re.search(r'\D', msg[2]) != None:
                await app.sendGroupMessage(
                    group,
                    msg_to_send.plus(
                        MessageChain.create([Plain("\n您输入的数字有问题哦~, 请您重新输入 ")
                                             ])))
            else:
                num = int(msg[2])
                img_url_list = await getImage.get_normal_image(msg[1], num)
                if img_url_list.__len__() < num:
                    msg_to_send.plus(
                        MessageChain.create([Plain("\n您要的太多了,小的只能找到这么多[卑微~]")
                                             ]))
                else:
                    msg_to_send.plus(MessageChain.create([Plain("\n您要的图~ ")]))
                for i in range(0, img_url_list.__len__()):
                    try:
                        msg_to_send.plus(
                            MessageChain.create(
                                [Image.fromNetworkAddress(img_url_list[i])]))
                    except:
                        pass
                await app.sendGroupMessage(group, msg_to_send)
    elif message.asDisplay().startswith("/天气"):
        msg = message.asDisplay()
        msg = re.split(r' +', msg)
        if (msg.__len__() != 2):
            await app.sendGroupMessage(
                group,
                MessageChain.create(
                    [At(member.id),
                     Plain("不要搞事情! 看好输入格式 : '/天气 城市', 请重新输入~")]))
        else:
            city = msg[1]
            city_code = city_code_dict[city]
            wea_list = await getWeather.get_weather(city, city_code)
            wea_dict = wea_list[1]
            string = ""
            for date in wea_dict:
                string += date + "  ".join(wea_dict[date]) + "\n"
            await app.sendGroupMessage(
                group,
                MessageChain.create([
                    At(member.id),
                    Plain("\n[" + city + "] 近七日天气情况如下:  \n"),
                    Plain(string),
                    Plain("From: " + wea_list[0])
                ]))
    elif message.asDisplay().startswith("/求问"):
        msg = message.asDisplay()
        msg = re.split(r' +', msg)
        msg_to_send = MessageChain.create([At(member.id)])
        if msg.__len__() > 3 or msg.__len__() <= 1:
            msg_to_send.plus(
                MessageChain.create([
                    Plain(
                        "\n不要捣乱哦,要遵守输入格式 : '/求问 第一关键词 第二关键词[Optional]', 请您重新输入一遍~"
                    )
                ]))
            await app.sendGroupMessage(group, msg_to_send)
        else:
            firstKeyword = msg[1]
            if firstKeyword in NameList:
                msg_to_send.plus(
                    MessageChain.create(
                        [Plain("\n" + firstKeyword + "太丑了,我才不查他呢,哼~")]))
                await app.sendGroupMessage(group, msg_to_send)
            elif firstKeyword in SpecialNameList:
                msg_to_send.plus(
                    MessageChain.create([
                        Plain("\n噢,你说" + firstKeyword + "啊,她是我主人的儿子[doge]~")
                    ]))
                await app.sendGroupMessage(group, msg_to_send)
            elif firstKeyword == myconfigs["OwnerName"] and msg.__len__() == 2:
                msg_to_send.plus(
                    MessageChain.create([Plain("\n一边去!我主人可不是你想问就能问的~")]))
                await app.sendGroupMessage(group, msg_to_send)
            elif firstKeyword == "白敬亭女朋友":
                msg_to_send.plus(
                    MessageChain.create(
                        [Plain("\n白敬亭现在还单身哦~~你每多zkk吃一顿饭, 你的希望就大一些[doge]")]))
                await app.sendGroupMessage(group, msg_to_send)
            elif firstKeyword == "张丹" and msg.__len__() == 2:
                msg_to_send.plus(
                    MessageChain.create(
                        [Plain("\n{}".format(SpecialMessage[firstKeyword]))]))
                await app.sendGroupMessage(group, msg_to_send)
            elif firstKeyword == "陈露" and msg.__len__() == 2:
                msg_to_send.plus(
                    MessageChain.create(
                        [Plain("\n{}".format(SpecialMessage[firstKeyword]))]))
                await app.sendGroupMessage(group, msg_to_send)
            else:
                if msg.__len__() == 3:
                    ans = await getBaidupedia.QueryPedia(firstKeyword, msg[2])
                else:
                    ans = await getBaidupedia.QueryPedia(firstKeyword)
                brief_introduction = ans[0]
                movie_url = ans[1]
                msg_to_send.plus(
                    MessageChain.create(
                        [Plain("\n" + brief_introduction + "\n")]))
                await app.sendGroupMessage(group, msg_to_send)
                await asyncio.sleep(1.5)
                if (movie_url != ""):
                    await app.sendGroupMessage(
                        group,
                        MessageChain.create([
                            Plain(f'有关 [{firstKeyword}] 的短视频介绍在这里哦~\n' +
                                  movie_url)
                        ]))
    elif message.asDisplay().startswith("/点歌"):
        msg = message.asDisplay()
        msg = re.search(r'(《.*》)', msg)
        song_data_dict = await getMusic.getKugouMusic(msg[1])
        msg_to_send = "\n{}\n歌手:{}\n专辑:{}\n".format(
            song_data_dict["song_name"], song_data_dict["singer_name"],
            song_data_dict["album_name"])
        await app.sendGroupMessage(
            group,
            MessageChain.create([
                At(member.id),
                Plain(msg_to_send),
                Image.fromNetworkAddress(song_data_dict["img_url"]),
                Plain(song_data_dict["lyrics"]),
                Plain(song_data_dict["song_url"])
            ]))
    elif message.has(At) and message.get(At)[0].target == myconfigs["account"]:
        await app.sendGroupMessage(
            group, MessageChain.create([At(member.id),
                                        Plain(Menu())]))

    elif message.asDisplay().startswith("/微博"):
        msg = message.asDisplay()
        msg = re.split(r' +', msg)
        if msg.__len__() > 3 or msg.__len__() <= 1:
            await app.sendGroupMessage(
                group,
                MessageChain.create([
                    At(member.id),
                    Plain("\n小伙子你不讲武德, 你把输入格式看看好: '/微博 昵称 数量(1~10|按时序先后)")
                ]))
        else:
            nickname = msg[1]
            if msg.__len__() == 2:
                num = 2
            else:
                num = int(msg[2])
            blog_list = await getSinaweibo.get_blog(nickname, num)
            msg_to_send = MessageChain.create([(At(member.id))])
            if blog_list.__len__() == 0:
                msg_to_send.plus(
                    MessageChain.create([Plain(f"抱歉, [{nickname}]好像不想被您知道~~")
                                         ]))
                await app.sendGroupMessage(group, msg_to_send)
            if num == 0:
                msg = ""
                msg += "[昵称] : {}\n".format(blog_list[0]["nickname"])
                # msg += "[关注数] : {}\n".format(blog_list[0]["follow_count"])
                msg += "[粉丝数] : {}\n".format(blog_list[0]["followers_count"])
                msg += "[微博认证] : {}\n".format(blog_list[0]["verified_reason"])
                msg += "[简介] : {}\n".format(blog_list[0]["description"])
                msg += "[头像] : \n"
                msg_to_send.plus(MessageChain.create([Plain(msg)]))
                msg_to_send.plus(
                    MessageChain.create([
                        Image.fromNetworkAddress(blog_list[0]["profile_img"])
                    ]))
                await app.sendGroupMessage(group, msg_to_send)
            else:
                if blog_list.__len__() < num:
                    num = blog_list.__len__()
                    msg_to_send.plus(
                        MessageChain.create([Plain(f"\n抱歉,暂时只能找到{num}条微博")]))
                for i in range(0, num):
                    item = blog_list[i]
                    msg_st = "\n"
                    msg_st += "[Content] : \n{}\n".format(item["blog_text"])
                    msg_end = "[Time] : {}\n".format(item["blog_time"])
                    msg_end += "[Source] : {}\n".format(item["source"])
                    msg_end += "[Likes] : {}\n".format(item["attitudes_count"])
                    msg_end += "[Comments] : {}\n".format(
                        item["comments_count"])
                    msg_end += "[Reposts] : {}\n".format(item["reposts_count"])
                    msg_to_send.plus(MessageChain.create([Plain(msg_st)]))
                    if item["blog_imgs"].__len__() > 0:
                        msg_to_send.plus(
                            MessageChain.create([
                                Image.fromNetworkAddress(img)
                                for img in item["blog_imgs"]
                            ]))
                    msg_to_send.plus(MessageChain.create([Plain(msg_end)]))
                await app.sendGroupMessage(group, msg_to_send)
    elif message.asDisplay().startswith("/test"):
        await app.sendGroupMessage(
            group,
            MessageChain.create([
                Xml("""
                <?xml version='1.0' encoding='UTF-8' standalone='yes' ?><msg serviceID="16" templateID="1" action="web" brief="推荐群聊:MyBot、&amp;.&amp;、Crépuscule" sourceMsgId="0" url="https://jq.qq.com/?_wv=1027&amp;k=lHRNHBqa" flag="0" adverSign="0" multiMsgFlag="0"><item layout="0" mode="1" advertiser_id="0" aid="0"><summary>推荐群</summary><hr hidden="false" style="0" /></item><item layout="2" mode="1" advertiser_id="0" aid="0"><picture cover="https://p.qlogo.cn/gh/823218983/823218983/100" w="0" h="0" needRoundView="0" /><title>MyBot、&amp;.&amp;、Crépuscule</title><summary>欢迎加入群聊</summary></item><source name="" icon="" action="" appid="-1" /></msg>"""
                    )
            ]))
    elif message.asDisplay().startswith('/B站'):
        msg = re.split(r' +', message.asDisplay())
        BV_id = msg[1]
        msg_to_send = MessageChain.create([At(member.id)])
        await app.sendGroupMessage(
            group,
            MessageChain.create(
                [At(member.id), Plain("\n您要的视频已开始尝试下载, 请耐心等待~")]))
        return_msg = await getBilibili.DownloadBilibili(BV_id)
        if return_msg:
            msg_to_send.plus(
                MessageChain.create([
                    Plain(f"\n您的视频已下载完成~,保存位置为[D:\\Mirai\\{BV_id}merged.mkv]")
                ]))
        else:
            msg_to_send.plus(MessageChain.create([Plain(f"\n抱歉,您的视频下载失败……")]))
        await app.sendGroupMessage(group, msg_to_send)
コード例 #27
0
    async def messagechain_to_img(
        message: MessageChain,
        max_width: int = 1080,
        font_size: int = 40,
        spacing: int = 15,
        padding_x: int = 20,
        padding_y: int = 15,
        img_fixed: bool = False,
        font_path: str = f"{os.getcwd()}/statics/fonts/STKAITI.TTF",
    ) -> MessageChain:
        """
        将 MessageChain 转换为图片,仅支持只含有本地图片/文本的 MessageChain
        Args:
            message: 要转换的MessageChain
            max_width: 最大长度
            font_size: 字体尺寸
            spacing: 行间距
            padding_x: x轴距离边框大小
            padding_y: y轴距离边框大小
            img_fixed: 图片是否适应大小(仅适用于图片小于最大长度时)
            font_path: 字体文件路径
        Examples:
            msg = await messagechain_to_img(message=message)
        Returns:
            MessageChain (内含图片Image类)
        """

        def get_final_text_lines(text: str, text_width: int, font: ImageFont.FreeTypeFont) -> int:
            lines = text.split("\n")
            line_count = 0
            for line in lines:
                if not line:
                    line_count += 1
                    continue
                line_count += int(math.ceil(float(font.getsize(line)[0]) / float(text_width)))
            return line_count + 1

        font = ImageFont.truetype(font_path, font_size, encoding="utf-8")
        message = message.asMerged()
        elements = message.__root__

        plains = message.get(Plain)
        text_gather = "\n".join([plain.text for plain in plains])
        # print(max(font.getsize(text)[0] for text in text_gather.split("\n")) + 2 * padding_x)
        final_width = min(max(font.getsize(text)[0] for text in text_gather.split("\n")) + 2 * padding_x, max_width)
        text_width = final_width - 2 * padding_x
        text_height = (font_size + spacing) * get_final_text_lines(text_gather, text_width, font)

        img_height_sum = 0
        temp_img_list = []
        images = [element for element in message.__root__ if (isinstance(element, Image_LocalFile) or isinstance(element, Image_UnsafeBytes))]
        for image in images:
            if isinstance(image, Image_LocalFile):
                temp_img = IMG.open(image.filepath)
            elif isinstance(image, Image_UnsafeBytes):
                temp_img = IMG.open(BytesIO(image.image_bytes))
            else:
                raise ValueError("messagechain_to_img:仅支持Image_LocalFile和Image_UnsafeBytes类的处理!")
            img_width, img_height = temp_img.size
            temp_img_list.append(
                temp_img := temp_img.resize((
                    int(final_width - 2 * spacing),
                    int(float(img_height * (final_width - 2 * spacing)) / float(img_width))
                )) if img_width > final_width - 2 * spacing or (img_fixed and img_width < final_width - 2 * spacing)
                else temp_img
            )
            img_height_sum = img_height_sum + temp_img.size[1]
        final_height = 2 * padding_y + text_height + img_height_sum
        picture = IMG.new('RGB', (final_width, final_height), (255, 255, 255))
        draw = ImageDraw.Draw(picture)
        present_x = padding_x
        present_y = padding_y
        image_index = 0
        for element in elements:
            if isinstance(element, Image) or isinstance(element, Image_UnsafeBytes) or isinstance(element, Image_LocalFile):
                picture.paste(temp_img_list[image_index], (present_x, present_y))
                present_y += (spacing + temp_img_list[image_index].size[1])
                image_index += 1
            elif isinstance(element, Plain):
                for char in element.text:
                    if char == "\n":
                        present_y += (font_size + spacing)
                        present_x = padding_x
                        continue
                    if char == "\r":
                        continue
                    if present_x + font.getsize(char)[0] > text_width:
                        present_y += (font_size + spacing)
                        present_x = padding_x
                    draw.text((present_x, present_y), char, font=font, fill=(0, 0, 0))
                    present_x += font.getsize(char)[0]
                present_y += (font_size + spacing)
                present_x = padding_x
        bytes_io = BytesIO()
        picture.save(bytes_io, format='PNG')
        logger.success("消息转图片处理成功!")
        return MessageChain.create([
            Image.fromUnsafeBytes(bytes_io.getvalue())
        ])
コード例 #28
0
ファイル: Group.py プロジェクト: SuperWaterGod/BFserver-Bot
async def BlackId_Group_listener(message: MessageChain,
                                 app: GraiaMiraiApplication, group: Group,
                                 member: Member):
    if message.has(At):
        AtLsit = []
        for i in range(len(message.get(At))):
            AtLsit.append(
                int(re.findall('target=(.*) ', str(message.get(At)[i]))[0]))
        MessageGet = message.asDisplay().replace(" ", "")
        for i in range(len(AtLsit)):
            if AtLsit[i] == Bot:
                pinyinStr = ""
                for i in range(len(lazy_pinyin(MessageGet))):
                    pinyinStr += lazy_pinyin(MessageGet)[i]
                if pinyinStr.find("shabi") >= 0 or pinyinStr.find(
                        "hanhan") >= 0 or pinyinStr.find("bendan") >= 0:
                    if pinyinStr.find("woshishabi") < 0:
                        await app.sendGroupMessage(group,
                                                   MessageChain.create([
                                                       At(member.id),
                                                       Plain("不理你了!")
                                                   ]),
                                                   quote=message[Source][0])
                        BlackId.add(member.id)
                elif MessageGet.find("对不起") >= 0 or MessageGet.find(
                        "我错了") >= 0 or MessageGet.find("抱歉") >= 0:
                    if member.id in BlackId:
                        await app.sendGroupMessage(
                            group,
                            MessageChain.create([
                                At(member.id),
                                Image.fromLocalFile("./Menhera/37.jpg"),
                                Plain("想让我原谅你?请问谁是傻逼?")
                            ]))

                        @Waiter.create_using_function([GroupMessage])
                        async def Remove_Blacklist(
                                event: GroupMessage, waiter_group: Group,
                                waiter_member: Member,
                                waiter_message: MessageChain):
                            if waiter_group.id == group.id and waiter_member.id == member.id and waiter_message.asDisplay(
                            ).find("我是傻逼") >= 0:
                                await app.sendGroupMessage(
                                    group,
                                    MessageChain.create([
                                        At(member.id),
                                        Image.fromLocalFile(
                                            "./Menhera/110.jpg"),
                                        Plain("哼,这还差不多┑( ̄Д  ̄)┍")
                                    ]))
                                BlackId.remove(member.id)
                                await app.sendGroupMessage(
                                    group,
                                    MessageChain.create(
                                        [Plain("这次就算了,下不为例哦╰( ̄ω ̄o)")]))
                                return event

                        try:
                            await asyncio.wait_for(inc.wait(Remove_Blacklist),
                                                   timeout=30)
                        except asyncio.TimeoutError:
                            await app.sendGroupMessage(
                                group,
                                MessageChain.create([
                                    At(member.id),
                                    Image.fromLocalFile("./Menhera/63.jpg"),
                                    Plain("\n不承认自己是傻逼就算了(*  ̄︿ ̄)")
                                ]))
                        pass
                    else:
                        await app.sendGroupMessage(
                            group,
                            MessageChain.create(
                                [Image.fromLocalFile("./Menhera/139.png")]),
                            quote=message[Source][0])
                else:
                    await app.sendGroupMessage(group,
                                               MessageChain.create(
                                                   [Plain("@我没有用哦~")]),
                                               quote=message[Source][0])