Exemple #1
0
async def live_handler(*args, bot: Bot, subject: Union[Member, Friend]):
    '''B站直播间开播订阅

    用法: /live 房间号'''
    if len(args) == 0:
        msg = []
        monitor_dict = readJSON(BILI_LIVE_JSON_PATH)
        if not isinstance(monitor_dict, dict):
            raise TypeError("Expected dict but found:", monitor_dict)
        for room_id, target in monitor_dict.items():
            if room_id == "time":
                continue
            if (isinstance(subject, Member) and groupToStr(subject.group) in target) \
                    or (isinstance(subject, Friend) and subject.id in target):
                res = getLiveInfo(room_id)
                if isinstance(res, str):
                    continue
                if res['isLive'] == 0:
                    msg.append(Plain(res['name'] + " 未在直播.\n"))
                else:
                    msg.append(
                        Plain(res['name'] + " 正在直播 " + "[{}]{}\n{}".format(
                            res["area_name"], res["title"], res["url"])))
                    msg.append(Image.fromNetworkAddress(res["keyframe"]))
        return MessageChain.create(msg)

    room_id = args[0]
    res = getLiveInfo(room_id)
    if isinstance(res, str):
        msg = [Plain("未找到该直播!")]
        logger.info("[LIVE]未找到该直播")
    else:
        monitor_dict = readJSON(BILI_LIVE_JSON_PATH)
        if not isinstance(monitor_dict, dict):
            raise TypeError("Expected dict but found:", monitor_dict)
        if room_id in monitor_dict.keys():
            if isinstance(subject, Member) and groupToStr(
                    subject.group) not in monitor_dict[room_id]:
                monitor_dict[room_id].append(groupToStr(subject.group))
            elif isinstance(subject,
                            Friend) and subject.id not in monitor_dict[room_id]:
                monitor_dict[room_id].append(subject.id)
        else:
            if isinstance(subject, Member):
                monitor_dict[room_id] = [groupToStr(subject.group)]
            elif isinstance(subject, Friend):
                monitor_dict[room_id] = [subject.id]
        updateJSON(BILI_LIVE_JSON_PATH, monitor_dict)
        if res['isLive'] == 0:
            msg = [Plain("已加入监视列表\n" + res['name'] + " 未在直播.")]
        else:
            msg = [
                Plain("已加入监视列表\n" +
                      res['name'] + " 正在直播 " + "[{}]{}\n{}".format(
                          res["area_name"], res["title"], res["url"])),
                Image.fromNetworkAddress(res["keyframe"])
            ]
        logger.info("[LIVE]返回成功")
    return MessageChain.create(msg)
async def video_info(app: GraiaMiraiApplication, group: Group,
                     message: MessageChain, member: Member):
    msg_str = message.asDisplay().strip()
    if msg_str.startswith(('av', 'AV', 'Av')):
        try:
            id_type = 'aid'
            num = int(re.sub('av', '', msg_str, flags=re.I))
        except ValueError:
            return
    elif msg_str.startswith('BV') and len(msg_str) == 12:
        id_type = 'bvid'
        num = msg_str
    else:
        return

    url = f'https://api.bilibili.com/x/web-interface/view?{id_type}={num}'
    async with aiohttp.request("GET", url) as r:
        get = await r.json()
    data = get['data']
    during = '{}分{}秒'.format(data['duration'] // 60, data['duration'] % 60)

    await app.sendGroupMessage(
        group,
        MessageChain.create([
            Image.fromNetworkAddress(get['data']['pic']),
            Plain(f"\n标题:{data['title']}"),
            Plain(f"\nUp主:{data['owner']['name']}"),
            Plain(f"\n视频时长:{during}"),
            Plain(f"\nav号:{data['aid']}"),
            Plain(f"\nbv号:{data['bvid']}"),
            Plain(f"\n链接:https://bilibili.com/video/{data['bvid']}")
        ]))
Exemple #3
0
async def Monitor(nickname: str, app: GraiaMiraiApplication, QQ_id: int,
                  Group_id: int, blog_id_set: Set) -> List:
    '''
    每隔一段时间监控一次, 如有新微博,发送给指定群组, 并@指定人
    '''
    try:
        tempList = await raw_monitor(nickname, blog_id_set)
    except:
        tempList = [False, []]
    if tempList[0] is True:
        new_blog_list = tempList[1]
        msg_to_send = MessageChain.create([At(QQ_id)])
        msg_st = "\n"
        msg_st += f"您关注的[ {nickname} ]有新动态哦, 请注意查收~~\n"
        msg_to_send.plus(MessageChain.create([Plain(msg_st)]))
        for blog in new_blog_list:
            try:
                msg_end = ""
                msg_end += "[Content] : \n{}\n".format(blog["blog_text"])
                msg_end += "[Time] : {}\n".format(blog["blog_time"])
                msg_end += "[Source] : {}\n".format(blog["source"])
                msg_end += "[Likes] : {}\n".format(blog["attitudes_count"])
                msg_end += "[Comments] : {}\n".format(blog["comments_count"])
                msg_end += "[Reposts] : {}\n".format(blog["reposts_count"])
                if blog["blog_imgs"].__len__() > 0:
                    msg_to_send.plus(
                        MessageChain.create([
                            Image.fromNetworkAddress(img)
                            for img in blog["blog_imgs"]
                        ]))
                msg_to_send.plus(MessageChain.create([Plain(msg_end)]))
            except:
                print("[发送错误, pos = 1]")
        await app.sendGroupMessage(Group_id, msg_to_send)
Exemple #4
0
async def AutoReply_Group_listener(message: MessageChain,
                                   app: GraiaMiraiApplication, group: Group,
                                   member: Member):
    if SearchSetting(group.id)["function"]["AutoReply"]:
        if member.id not in BlackId:
            MessageGet = AutoReply(message.asDisplay())
            if MessageGet.startswith("./Menhera/"):
                await app.sendGroupMessage(
                    group,
                    MessageChain.create([Image.fromLocalFile(MessageGet)]))
            elif MessageGet == "":
                pass
            else:
                await app.sendGroupMessage(
                    group, MessageChain.create([Plain(MessageGet)]))
            MessageGet = AutoVoice(message.asDisplay())
            if MessageGet.startswith("./voice/"):
                await app.sendGroupMessage(
                    group,
                    MessageChain.create([Voice().fromLocalFile(MessageGet)]))
            elif MessageGet == "":
                pass

            slogan = re.findall('(.*)\n(.*).jpg', message.asDisplay())  # 在线P图
            if slogan:
                upper = slogan[0][0]
                lower = slogan[0][1]
                await app.sendGroupMessage(
                    group,
                    MessageChain.create([
                        Image.fromNetworkAddress(
                            "https://api.dihe.moe/5000choyen?upper=" + upper +
                            "&lower=" + lower)
                    ]))
Exemple #5
0
async def group_message_handler(app: GraiaMiraiApplication,
                                message: MessageChain, group: Group):
    if message.asDisplay().startswith("色图"):
        await app.sendGroupMessage(
            group,
            MessageChain.create([
                Image.fromNetworkAddress(
                    'https://raw.githubusercontent.com/zk-wz/randomsetu/master/piccache/%20%20%20('
                    + str(random.randrange(1, 301)) + ').jpg')
            ]))
Exemple #6
0
async def latex(app, group, s: str):
    text = s.replace('latex ', '', 1)
    url = 'https://latex.codecogs.com/png.latex?%5Cdpi%7B300%7D%20%5Cbg_white%20%5Csmall%20'
    text = parse.quote(text)
    text = text.replace('%2B', '+')
    try:
        await app.sendGroupMessage(
            group, MessageChain.create([Image.fromNetworkAddress(url + text)]))
    except:
        await app.sendGroupMessage(
            group, MessageChain.create([Plain('输入了无效的公式,请重试')]))
Exemple #7
0
async def Admin_Friend_Test(message: MessageChain, app: GraiaMiraiApplication,
                            friend: Friend):
    if friend.id == Admin:
        slogan = re.findall('(.*)\n(.*).jpg', message.asDisplay())
        if slogan:
            upper = slogan[0][0]
            lower = slogan[0][1]
            await app.sendFriendMessage(
                friend,
                MessageChain.create([
                    Image.fromNetworkAddress(
                        "https://api.dihe.moe/5000choyen?upper=" + upper +
                        "&lower=" + lower)
                ]))
Exemple #8
0
async def recommend_handler(*args, bot: Bot, subject: Union[Member, Friend]):
    '''td金牌推荐舞见视频

    用法: /recommend'''
    title, author, pic, url, racy = getRecommendDance()
    msg = [Plain(text="本次核心推荐up随机视频:\n")]
    for i, ti in enumerate(title):
        msg.append(Plain(str(i + 1) + ":" + ti + " by " + author[i] + "\n"))
        msg.append(Plain(url[i] + "\n"))
        msg.append(Plain("se指数(by Google):" + RACY_LIST[racy[i] - 1] + "\n"))
        msg.append(Image.fromNetworkAddress(pic[i]))  # type: ignore
        msg.append(Plain("\n"))
    logger.info("[RECOMMEND]返回成功")
    return MessageChain.create(msg)
Exemple #9
0
async def dance_handler(*args, bot: Bot, subject: Union[Member, Friend]):
    '''B站舞蹈区排行

    用法: /dance'''
    title, author, pic, url, racy = getTop3DanceToday()
    msg = [Plain("B站舞蹈区实时排名前3(已剔除潜在不适内容)\n")]
    for i, ti in enumerate(title):
        msg.append(Plain(str(i + 1) + ":" + ti + " by " + author[i] + "\n"))
        msg.append(Plain(url[i] + "\n"))
        msg.append(Plain("se指数(by Google):" + RACY_LIST[racy[i] - 1] + "\n"))
        msg.append(Image.fromNetworkAddress(pic[i]))  # type: ignore
        msg.append(Plain("\n"))
    logger.info("[DANCE]返回成功")
    return MessageChain.create(msg)
Exemple #10
0
async def bdbk(app: GraiaMiraiApplication, group: Group, member: Member,
               tag: MessageChain):
    tags = tag.asDisplay().strip().split(' ', 1)

    bdurl = f'https://baike.baidu.com/item/{urllib.parse.quote(tags[0])}?force=1'
    async with aiohttp.request("GET",
                               bdurl,
                               headers=headers,
                               allow_redirects=True) as r:
        if str(r.url) == 'https://baike.baidu.com/error.html':
            await app.sendGroupMessage(
                group, MessageChain.create([Plain('sorry,百科并没有相关信息')]))
            return
        reponse = await r.text()

    page = etree.HTML(reponse)
    if page.xpath('//div[@class="lemmaWgt-subLemmaListTitle"]//text()') != []:
        if len(tags) == 1:
            catalog = page.xpath(
                '//div[@class="para" and @label-module="para"]/a/text()')
            await app.sendGroupMessage(
                group,
                MessageChain.create([
                    Plain(f"请输入代号\ne.g:百科 {tags[0]} 1\n\n"),
                    Plain('\n'.join(f"{n}.{w.replace(f'{tags[0]}:','')}"
                                    for n, w in enumerate(catalog)))
                ]))
            return
        use = int(tags[1]) - 1
        path = page.xpath(
            '//div[@class="para" and @label-module="para"]/a/@href')[use]
        bdurl = r'https://baike.baidu.com' + path
        async with aiohttp.request("GET", bdurl, headers=headers) as r:
            reponse = await r.text()
        page = etree.HTML(reponse)

    for i in page.xpath('//div[@class="lemma-summary"]/div//sup'):
        i.getparent().remove(i)

    mem = page.xpath('//div[@class="lemma-summary"]/div//text()')
    mem = "".join(mem).replace('\n', '').replace('\xa0', '')

    mes = [
        Plain(f'{mem}\n' if mem else '没有简介desu\n'),
        Plain(bdurl.replace("?force=1", ""))
    ]

    if (img_url := page.xpath('//div[@class="summary-pic"]/a/img/@src')):
        mes.append(Image.fromNetworkAddress(img_url[0]))
Exemple #11
0
async def up_handler(*args, bot: Bot, subject: Union[Member, Friend]):
    '''订阅UP主投稿

    用法: /up UP主uid'''
    if len(args) == 0:
        res = "目前关注的UP主有:\n"
        up_dict = readJSON(BILI_UP_JSON_PATH)
        if not isinstance(up_dict, dict):
            raise TypeError("Expected dict but found:", up_dict)
        for up, target in up_dict.items():
            if up == "time":
                continue
            if (isinstance(subject, Member) and groupToStr(subject.group) in target) \
                    or (isinstance(subject, Friend) and subject.id in target):
                res += getNameByUid(up) + " "
        return MessageChain.create([Plain(res)])

    up_id = args[0]
    up_name = getNameByUid(up_id)
    res = getCards(up_id)
    if isinstance(res, str):
        msg = [Plain("未找到该UP主!")]
        logger.info("[UP]未找到该UP主")
    else:
        up_dict = readJSON(BILI_UP_JSON_PATH)
        if not isinstance(up_dict, dict):
            raise TypeError("Expected dict but found:", up_dict)
        if up_id in up_dict.keys():
            if isinstance(subject, Member) and groupToStr(
                    subject.group) not in up_dict[up_id]:
                up_dict[up_id].append(groupToStr(subject.group))
            if isinstance(subject, Friend) and subject.id not in up_dict[up_id]:
                up_dict[up_id].append(subject.id)
        else:
            if isinstance(subject, Member):
                up_dict[up_id] = [groupToStr(subject.group)]
            elif isinstance(subject, Friend):
                up_dict[up_id] = [subject.id]
        updateJSON(BILI_UP_JSON_PATH, up_dict)
        if len(res) == 0:
            msg = [Plain("已加入关注列表 " + up_name + " 暂无新投稿.")]
        else:
            msg = [Plain(f"已加入关注列表 {up_name}\n")]
            for i in res:
                msg.append(Plain(f"{up_name} 投稿了视频《{i['title']}》:{i['url']}\n"))
                msg.append(Image.fromNetworkAddress(i["pic"]))  # type: ignore
                msg.append(Plain("\n"))
        logger.info("[UP]返回成功")
    return MessageChain.create(msg)
Exemple #12
0
 async def check_news():
     logger_info('Checking Minecraft news...')
     baseurl = 'https://www.minecraft.net'
     url = 'https://www.minecraft.net/content/minecraft-net/_jcr_content.articles.grid?tileselection=auto&tagsPath=minecraft:article/news,minecraft:article/insider,minecraft:article/culture,minecraft:article/merch,minecraft:stockholm/news,minecraft:stockholm/guides,minecraft:stockholm/deep-dives,minecraft:stockholm/merch,minecraft:stockholm/events,minecraft:stockholm/minecraft-builds,minecraft:stockholm/marketplace&offset=0&count=500&pageSize=10'
     async with aiohttp.ClientSession() as session:
         async with session.get(url) as resp:
             status = resp.status
             if status == 200:
                 nws = json.loads(await resp.read())['article_grid']
                 for article in nws:
                     default_tile = article['default_tile']
                     title = default_tile['title']
                     image = baseurl + default_tile['image']['imageURL']
                     desc = default_tile['sub_header']
                     link = baseurl + article['article_url']
                     date = article['publish_date']
                     q = database.check_exist(title)
                     if not q:
                         database.add_news(title, link, desc, image, date)
                         articletext = f'Minecraft官网发布了新的文章:\n{title}\n{link}\n{desc}\n'
                         msgchain = MessageChain.create([
                             Plain(articletext),
                             Image.fromNetworkAddress(image)
                         ])
                         for qqgroup in check_enable_modules_all(
                                 'group_permission', 'minecraft_news'):
                             try:
                                 await app.sendGroupMessage(
                                     int(qqgroup), msgchain)
                                 await asyncio.sleep(0.5)
                             except Exception:
                                 traceback.print_exc()
                         for qqfriend in check_enable_modules_all(
                                 'friend_permission', 'minecraft_news'):
                             try:
                                 await app.sendFriendMessage(
                                     int(qqfriend), msgchain)
                                 await asyncio.sleep(0.5)
                             except Exception:
                                 traceback.print_exc()
                         logger_info(articletext)
                 logger_info('Minecraft news checked.')
             else:
                 logger_info('Check minecraft news failed:' + status)
Exemple #13
0
async def live_scheduler(bot: Bot):
    monitor_dict = readJSON(BILI_LIVE_JSON_PATH, defaultValue={})
    if not isinstance(monitor_dict, dict):
        raise TypeError("Expected dict but found:", monitor_dict)
    for room_id in monitor_dict.keys():
        res = getLiveInfo(room_id)
        if isinstance(res, dict) and res['isLive'] == 1 and time.time() - int(
                time.mktime(time.strptime(res['live_time'],
                                          "%Y-%m-%d %H:%M:%S"))) < 600:
            msg = MessageChain.create([
                Plain(res['name'] + " 开播啦! " + "[{}]{}\n{}".format(
                    res["area_name"], res["title"], res["url"])),
                Image.fromNetworkAddress(res["keyframe"])
            ])
            for member in monitor_dict[room_id]:
                if type(member) == str:
                    await bot.sendMessage(groupFromStr(member), msg)
                else:
                    await bot.sendMessage(member, msg)
Exemple #14
0
async def up_scheduler(bot: Bot):
    up_dict = readJSON(BILI_UP_JSON_PATH, defaultValue={})
    if not isinstance(up_dict, dict):
        raise TypeError("Expected dict but found:", up_dict)
    for up_id in up_dict.keys():
        res = getCards(up_id)
        up_name = getNameByUid(up_id)
        if isinstance(res, list) and len(res) != 0:
            msg = []
            for i in res:
                msg.append(
                    Plain(text=f"{up_name} 投稿了视频《{i['title']}》:{i['url']}\n"))
                msg.append(Image.fromNetworkAddress(i["pic"]))
                msg.append(Plain(text="\n"))
            msg = MessageChain.create(msg)
            for member in up_dict[up_id]:
                if type(member) == str:
                    await bot.sendMessage(groupFromStr(member), msg)
                else:
                    await bot.sendMessage(member, msg)
Exemple #15
0
async def Schedule_Task():
    UseTime = time.strftime('%H:%M', time.localtime(time.time()))
    if UseTime == "08:00":
        for i in range(len(ScheduleGroup)):
            await app.sendGroupMessage(
                ScheduleGroup[i],
                MessageChain.create([
                    Image.fromLocalFile("./Menhera/121.png"),
                    Plain("早早早(*´▽`)ノノ")
                ]))
    elif UseTime == "12:00":
        for i in range(len(ScheduleGroup)):
            await app.sendGroupMessage(
                ScheduleGroup[i],
                MessageChain.create([
                    Image.fromLocalFile("./Menhera/44.jpg"),
                    Plain("干饭时间到,开始干饭啦ヾ(^▽^*)))~")
                ]))
    elif UseTime == "23:00":
        for i in range(len(ScheduleGroup)):
            await app.sendGroupMessage(
                ScheduleGroup[i],
                MessageChain.create([
                    Image.fromLocalFile("./Menhera/122.png"),
                    Plain("米娜桑,晚安( ̄o ̄) . z Z")
                ]))
    VideoDetail = None
    if VideoDetail is not None:
        VideoMessage = "你关注的UP主:" + VideoDetail[2] + "发布了新的视频:\n" + VideoDetail[
            0] + "\n视频链接:https://www.bilibili.com/video/" + VideoDetail[
                1] + "\n快去给他一个三连吧o(*////▽////*)q"
        for i in range(len(ScheduleGroup)):
            await app.sendGroupMessage(
                ScheduleGroup[i],
                MessageChain.create([
                    Image.fromNetworkAddress("http://" + VideoDetail[3]),
                    Plain(VideoMessage)
                ]))
    global PerNumMessages
    PerNumMessages = 0
    pass
Exemple #16
0
    async def check_weekly():
        logger_info('Checking MCWZH weekly...')
        result = json.loads(await get_url(
            'https://minecraft.fandom.com/zh/api.php?action=parse&page=Minecraft_Wiki/weekly&prop=text|revid&format=json'
        ))
        html = result['parse']['text']['*']
        text = re.sub(r'<p>', '\n', html)  # 分段
        text = re.sub(r'<(.*?)>', '', text, flags=re.DOTALL)  # 移除所有 HTML 标签
        text = re.sub(r'\n\n\n', '\n\n', text)  # 移除不必要的空行
        text = re.sub(r'\n*$', '', text)
        img = re.findall(
            r'(?<=src=")(.*?)(?=/revision/latest/scale-to-(width|height)-down/\d{3}\?cb=\d{14}?")',
            html)
        page = re.findall(r'(?<=<b><a href=").*?(?=")', html)
        sended_img = Image.fromNetworkAddress(
            img[0][0]) if img else Plain('\n(发生错误:图片获取失败)')
        msg = '发生错误:本周页面已过期,请联系中文 Minecraft Wiki 更新。' if page[0] == '/zh/wiki/%E7%8E%BB%E7%92%83' else '本周的每周页面:\n\n' + text + '\n图片:' + \
                                                                                                      img[0][
                                                                                                          0] + '?format=original\n\n页面链接:https://minecraft.fandom.com' + \
                                                                                                      page[
                                                                                                          0] + '\n每周页面:https://minecraft.fandom.com/zh/wiki/?oldid=' + str(
        result['parse']['revid'])
        chain = MessageChain.create([Plain(msg), sended_img])
        for qqgroup in check_enable_modules_all('group_permission',
                                                'weekly_rss'):
            try:
                await app.sendGroupMessage(int(qqgroup), chain)
                await asyncio.sleep(0.5)
            except Exception:
                traceback.print_exc()

        for qqfriend in check_enable_modules_all('friend_permission',
                                                 'weekly_rss'):
            try:
                await app.sendFriendMessage(int(qqfriend), chain)
                await asyncio.sleep(0.5)
            except Exception:
                traceback.print_exc()

        logger_info(msg)
        logger_info('Weekly checked.')
Exemple #17
0
async def coolapk(app: GraiaMiraiApplication, group: Group, member: Member):
    await app.sendGroupMessage(
        group, MessageChain.create([At(member.id),
                                    Plain(" 图片发送较慢,请稍等...")]))

    n = await request(
        "https://api.coolapk.com/v6/page/dataList?url=%2Ffeed%2FcoolPictureList%3FfragmentTemplate%3Dflex&title=&subTitle=&page=1"
    )

    choice_dict = random.choice(n)

    url = choice_dict["pic"]
    username = choice_dict["username"]
    tag = choice_dict["tags"]
    device = choice_dict["device_title"]

    msg = [
        At(member.id),
        Plain(" 用户名:{}\n使用设备:{}\n标签:{}".format(username, device, tag)),
        Image.fromNetworkAddress(url),
    ]
    await app.sendGroupMessage(group, MessageChain.create(msg))
Exemple #18
0
async def cytoid_profile(kwargs: dict):
    if Group in kwargs:
        mth = UploadMethods.Group
    if Friend in kwargs:
        mth = UploadMethods.Friend
    name = kwargs['trigger_msg']
    profile_url = 'http://services.cytoid.io/profile/' + name
    profile = json.loads(await get_url(profile_url))
    if 'statusCode' in profile:
        if profile['statusCode'] == 404:
            await sendMessage(kwargs, '发生错误:此用户不存在。')
            return
    uid = profile['user']['uid']
    nick = profile['user']['name']
    if nick is None:
        nick = False
    avatar = profile['user']['avatar']['large']
    basicExp = profile['exp']['basicExp']
    levelExp = profile['exp']['levelExp']
    totalExp = profile['exp']['totalExp']
    currentLevel = profile['exp']['currentLevel']
    nextLevelExp = profile['exp']['nextLevelExp']
    rating = profile['rating']
    grade = profile['grade']
    grade = f'A: {grade["A"]}, B: {grade["B"]}, C: {grade["C"]}, D: {grade["D"]}, F: {grade["F"]}, S: {grade["S"]}, SS: {grade["SS"]}'
    text = f'UID: {uid}\n' + \
           (f'Nickname: {nick}\n' if nick else '') + \
           f'BasicExp: {basicExp}\n' + \
           f'LevelExp: {levelExp}\n' + \
           f'TotalExp: {totalExp}\n' + \
           f'CurrentLevel: {currentLevel}\n' + \
           f'NextLevelExp: {nextLevelExp}\n' + \
           f'Rating: {rating}\n' + \
           f'Grade: {grade}'
    msg = MessageChain.create(
        [Image.fromNetworkAddress(avatar, method=mth),
         Plain(text)])
    await sendMessage(kwargs, msg)
Exemple #19
0
async def weekly(kwargs: dict):
    try:
        result = json.loads(await get_url(
            'https://minecraft.fandom.com/zh/api.php?action=parse&page=Minecraft_Wiki/weekly&prop=text|revid&format=json'))
        html = result['parse']['text']['*']
        text = re.sub(r'<p>', '\n', html)  # 分段
        text = re.sub(r'<(.*?)>', '', text, flags=re.DOTALL)  # 移除所有 HTML 标签
        text = re.sub(r'\n\n\n', '\n\n', text)  # 移除不必要的空行
        text = re.sub(r'\n*$', '', text)
        img = re.findall(r'(?<=src=")(.*?)(?=/revision/latest/scale-to-(width|height)-down/\d{3}\?cb=\d{14}?")', html)
        page = re.findall(r'(?<=<b><a href=").*?(?=")', html)
        sended_img = Image.fromNetworkAddress(img[0][0]) if img else Plain('\n(发生错误:图片获取失败)')
        msg = '发生错误:本周页面已过期,请联系中文 Minecraft Wiki 更新。' if page[
                                                             0] == '/zh/wiki/%E7%8E%BB%E7%92%83' else '本周的每周页面:\n\n' + text + '\n图片:' + \
                                                                                                      img[0][
                                                                                                          0] + '?format=original\n\n页面链接:https://minecraft.fandom.com' + \
                                                                                                      page[
                                                                                                          0] + '\n每周页面:https://minecraft.fandom.com/zh/wiki/?oldid=' + str(
            result['parse']['revid'])
        await sendMessage(kwargs, MessageChain.create([Plain(msg), sended_img]))

    except Exception as e:
        await sendMessage(kwargs, '发生错误:' + str(e))
Exemple #20
0
async def repo(kwargs: dict, cmd: list):
    try:
        try:
            obj = cmd[1].replace('@', '')
        except IndexError:
            obj = cmd[0].replace('@', '')
        result = await query('https://api.github.com/repos/' + obj, 'json')
        if 'message' in result and result['message'] == 'Not Found':
            raise RuntimeError('此仓库不存在。')
        elif 'message' in result and result['message']:
            raise RuntimeError(result['message'])
        name = result['full_name']
        url = result['html_url']
        rid = result['id']
        lang = result['language']
        fork = result['forks_count']
        star = result['stargazers_count']
        watch = result['watchers_count']
        mirror = result['mirror_url']
        rlicense = 'Unknown'
        if 'license' in result and result['license'] is not None:
            if 'spdx_id' in result['license']:
                rlicense = result['license']['spdx_id']
        is_fork = result['fork']
        created = result['created_at']
        updated = result['updated_at']
        parent = False
        website = result['homepage']

        if website is not None:
            website = 'Website: ' + website + '\n'
        else:
            website = ''

        if mirror is not None:
            mirror = f' (This is a mirror of {mirror} )'
        else:
            mirror = False

        if is_fork:
            parent_name = result['parent']['name']
            parent = f' (This is a fork of {parent_name} )'

        desc = result['description']
        if desc is None:
            desc = ''
        else:
            desc = '\n' + result['description']

        msg = f'''{name} ({rid}){desc}

Language · {lang} | Fork · {fork} | Star · {star} | Watch · {watch}
License: {rlicense}
Created {time_diff(created)} ago | Updated {time_diff(updated)} ago

{website}{url}
'''

        if mirror:
            msg += '\n' + mirror

        if parent:
            msg += '\n' + parent

        is_dirty = await dirty_check(
            msg, result['owner']['login']) or darkCheck(msg)
        if is_dirty:
            msg = 'https://wdf.ink/6OUp'
            await sendMessage(kwargs, MessageChain.create([Plain(msg)]))
        else:
            await sendMessage(
                kwargs,
                MessageChain.create([
                    Plain(msg),
                    Image.fromNetworkAddress(
                        'https://opengraph.githubassets.com/c9f4179f4d560950b2355c82aa2b7750bffd945744f9b8ea3f93cc24779745a0/'
                        + name)
                ]))
    except Exception as e:
        await sendMessage(kwargs, '发生错误:' + str(e))
        traceback.print_exc()
Exemple #21
0
    async def on_message(self, target, source, message):
        try:
            print(message.encode('utf-8'))
            await super().on_message(target, source, message)

            message = clrstrip.sub('', message)

            if source == 'Sequell':
                msgarray = message.split(':')
                serv = msgarray[0]
                group = msgarray[1]
                member = msgarray[2]
                msg = ':'.join(msgarray[3:])

                url_regex = '(http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+)'
                msg_split = re.split(url_regex, msg)

                msg = ''.join(msg_split)

                if msg[:3] == '/me':
                    msg = '*' + msg[3:].strip() + '*'

                if re.search('\[\d\d?/\d\d?\]:', msg):
                    s = re.split('(\[\d\d?/\d\d?\]:)', msg)
                    msg = s[0] + s[1] + '\n' + ''.join(s[2:]).strip()

                response = [Plain(msg)]
                img_url_regex = '(http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+\.(?:jpg|png|gif))'
                for url in re.findall(img_url_regex, msg):
                    response.append(Image.fromNetworkAddress(url=url))

                if serv == 'group':
                    await qqClient.sendGroupMessage(
                        group, MessageChain.create(response))
                elif serv == 'temp':
                    await qqClient.sendTempMessage(
                        group, member, MessageChain.create(response))
                elif serv == 'friend':
                    await qqClient.sendFriendMessage(
                        member, MessageChain.create(response))

            chan = None
            if source == 'Gretell':
                chan = GretellChan
            if source == 'Cheibriados':
                chan = CheibriadosChan

            if chan is not None:
                if chan.lock.locked():
                    if chan.GetType() == 'group':
                        await qqClient.sendGroupMessage(
                            chan.group, MessageChain.create([Plain(message)]))
                    elif chan.GetType() == 'friend':
                        await qqClient.sendFriendMessage(
                            chan.member, MessageChain.create([Plain(message)]))
                    elif chan.GetType() == 'temp':
                        await qqClient.sendTempMessage(
                            chan.group, chan.member,
                            MessageChain.create([Plain(message)]))
                    if chan.lock.locked():
                        chan.lock.release()

        except Exception:
            print("Exception irc thread:")
            traceback.print_exc(file=sys.stdout)
Exemple #22
0
async def blhxpush(app, preTimestamp):
    await asyncio.sleep(10)
    url = "https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/space_history?visitor_uid=33091201&host_uid=233114659&offset_dynamic_id=0&need_top=1&platform=web"
    Information = requests.get(url, headers=headers).json()
    while (True):
        t = time.time()
        t = int(t)
        url = "https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/space_history?visitor_uid=33091201&host_uid=233114659&offset_dynamic_id=0&need_top=1&platform=web"
        Information = requests.get(url, headers=headers).json()
        try:
            timestamp = Information['data']['cards'][1]['desc']['timestamp']
        except:
            timestamp = 0
        print("当前时间戳为:")
        print(t)
        print("上一个动态的时间戳为:")
        print(preTimestamp)
        print("当前动态的时间戳为:")
        print(timestamp)
        if preTimestamp != timestamp:
            preTimestamp = timestamp
            judge = Information['data']['cards'][1]

            if judge['desc']['type'] == 1:
                needInformation = Information['data']['cards'][1]['card']
                dictInformation = eval(needInformation)
                msg = dictInformation['item']['content']
                for group in groups:
                    message = MessageChain.create(
                        [Plain("碧蓝航线b服动态更新\n================\n"),
                         Plain(msg)])
                    await app.sendGroupMessage(group, message)

            elif judge['desc']['type'] == 2:
                needInformation = Information['data']['cards'][1]['card']
                dictInformation = eval(needInformation)
                try:
                    if (dictInformation['item']['pictures_count'] == 1):
                        pictures = dictInformation['item']['pictures'][0][
                            'img_src']
                        flag = 0
                    else:
                        pictures = dictInformation['item']['pictures']
                        flag = 1
                        count = dictInformation['item']['pictures_count']
                except:
                    pictures = " "
                msgDict = {
                    "information": dictInformation['item']['description'],
                    "picture_url": pictures
                }
                for group in groups:
                    if msgDict['picture_url'] != ' ':
                        if flag == 0:
                            msgDict['picture_url'] = eval(
                                repr(msgDict['picture_url']).replace('\\', ''))
                            await app.sendGroupMessage(
                                group,
                                MessageChain.create([
                                    Plain("碧蓝航线b服动态更新\n================\n"),
                                    Plain(msgDict['information']),
                                    Image.fromNetworkAddress(
                                        msgDict['picture_url'])
                                ]))
                        elif flag == 1:
                            message1 = MessageChain.create([
                                Plain("碧蓝航线b服动态更新\n================\n"),
                                Plain(msgDict['information'])
                            ])
                            for i in count:
                                pictures[i]['img_src'] = eval(
                                    repr(pictures[i]['img_src']).replace(
                                        '\\', ''))
                                msg = MessageChain.join([
                                    Image.fromNetworkAddress(
                                        pictures[i]['img_src'])
                                ])
                            Msg = MessageChain.join(message1, msg)
                            await app.sendGroupMessage(group, Msg)
                    else:
                        await app.sendGroupMessage(
                            group,
                            MessageChain.create([
                                Plain("碧蓝航线b服动态更新\n================\n"),
                                Plain(msgDict['information'])
                            ]))

            elif judge['desc']['type'] == 4:
                needInformation = Information['data']['cards'][1]['card']
                dictInformation = eval(needInformation)
                pictures = " "
                msgDict = {
                    "information": dictInformation['item']['content'],
                    "picture_url": pictures
                }
                for group in groups:
                    if msgDict['picture_url'] != ' ':
                        msgDict['picture_url'] = eval(
                            repr(msgDict['picture_url']).replace('\\', ''))
                        await app.sendGroupMessage(
                            group,
                            MessageChain.create([
                                Plain("碧蓝航线b服动态更新\n================\n"),
                                Plain(msgDict['information']),
                                Image.fromNetworkAddress(
                                    msgDict['picture_url'])
                            ]))
                    else:
                        await app.sendGroupMessage(
                            group,
                            MessageChain.create([
                                Plain("碧蓝航线b服动态更新\n================\n"),
                                Plain(msgDict['information'])
                            ]))

            await asyncio.sleep(60)

        else:
            await asyncio.sleep(60)
            continue
Exemple #23
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())
Exemple #24
0
async def battlefield(message: MessageChain, app: GraiaMiraiApplication,
                      group: Group, member: Member):
    if SearchSetting(group.id)["function"]["battlefield"]:
        MessageStr = message.asDisplay()
        if any([MessageStr.startswith("/最近"), MessageStr.startswith("/战绩"), MessageStr.startswith("/服务器"), MessageStr.startswith("/武器"), MessageStr.startswith("/载具"),
                MessageStr.startswith("/帮助"), MessageStr.startswith("/绑定")]) or \
                any([MessageStr.startswith("/手榴弹"), MessageStr.startswith("/步枪"), MessageStr.startswith("/轻机枪"), MessageStr.startswith("/手枪"),
                     MessageStr.startswith("/半自动"), MessageStr.startswith("/霰弹枪"), MessageStr.startswith("/精英兵"), MessageStr.startswith("/近战"),
                     MessageStr.startswith("/冲锋枪"), MessageStr.startswith("/装备")]):
            if member.id in BlackId:
                await app.sendGroupMessage(group,
                                           MessageChain.create([
                                               At(member.id),
                                               Plain("哼(╯▔皿▔)╯,不理你了!")
                                           ]),
                                           quote=message[Source][0])
            else:
                if MessageStr.startswith("/最近"):
                    await app.sendGroupMessage(
                        group,
                        MessageChain.create([
                            At(member.id),
                            Plain("\n" +
                                  await BFservers(member.id, MessageStr))
                        ]),
                        quote=message[Source][0])
                elif MessageStr.startswith("/战绩"):
                    MessageGet = await BFservers(member.id, MessageStr)
                    if MessageGet.startswith("头像"):
                        avatar = re.findall('头像:(.*)', MessageGet)[0]
                        MessageStr = re.findall('昵称:[\s\S]*', MessageGet)[0]
                        try:
                            await app.sendGroupMessage(
                                group,
                                MessageChain.create([
                                    At(member.id),
                                    Image.fromNetworkAddress(avatar),
                                    Plain("\n" + MessageStr)
                                ]),
                                quote=message[Source][0])
                        except:
                            await app.sendGroupMessage(
                                group,
                                MessageChain.create(
                                    [At(member.id),
                                     Plain("\n" + MessageGet)]),
                                quote=message[Source][0])
                    else:
                        await app.sendGroupMessage(group,
                                                   MessageChain.create([
                                                       At(member.id),
                                                       Plain("\n" + MessageGet)
                                                   ]),
                                                   quote=message[Source][0])
                elif MessageStr.startswith("/服务器") or MessageStr.startswith(
                        "/武器") or MessageStr.startswith("/载具"):
                    if MessageStr == "/服务器":
                        MessageStr += SearchSetting(group.id)["name"]
                    MessageGet = await BFservers(member.id, MessageStr)
                    if MessageGet.startswith("./"):
                        await app.sendGroupMessage(
                            group,
                            MessageChain.create([
                                At(member.id),
                                Image.fromLocalFile(MessageGet)
                            ]),
                            quote=message[Source][0])
                        await asyncio.sleep(30)
                        os.remove(MessageGet)
                    else:
                        await app.sendGroupMessage(group,
                                                   MessageChain.create([
                                                       At(member.id),
                                                       Plain("\n" + MessageGet)
                                                   ]),
                                                   quote=message[Source][0])
                elif MessageStr.startswith("/帮助"):
                    await app.sendGroupMessage(
                        group,
                        MessageChain.create([
                            At(member.id),
                            Plain("\n" +
                                  await BFservers(member.id, MessageStr))
                        ]),
                        quote=message[Source][0])
                elif MessageStr.startswith("/绑定"):
                    await app.sendGroupMessage(
                        group,
                        MessageChain.create([
                            At(member.id),
                            Plain(
                                Binding(
                                    member.id,
                                    MessageStr.replace("/绑定",
                                                       "").replace(" ", "")))
                        ]),
                        quote=message[Source][0])
                elif any([
                        MessageStr.startswith("/手榴弹"),
                        MessageStr.startswith("/步枪"),
                        MessageStr.startswith("/轻机枪"),
                        MessageStr.startswith("/手枪"),
                        MessageStr.startswith("/半自动"),
                        MessageStr.startswith("/霰弹枪"),
                        MessageStr.startswith("/精英兵"),
                        MessageStr.startswith("/近战"),
                        MessageStr.startswith("/冲锋枪"),
                        MessageStr.startswith("/装备")
                ]):
                    MessageGet = await BFservers(member.id, MessageStr)
                    if MessageGet.startswith("./"):
                        await app.sendGroupMessage(
                            group,
                            MessageChain.create([
                                At(member.id),
                                Image.fromLocalFile(MessageGet)
                            ]),
                            quote=message[Source][0])
                        await asyncio.sleep(30)
                        os.remove(MessageGet)
                    else:
                        await app.sendGroupMessage(group,
                                                   MessageChain.create([
                                                       At(member.id),
                                                       Plain("\n" + MessageGet)
                                                   ]),
                                                   quote=message[Source][0])
Exemple #25
0
async def pixiv_Group_listener(message: MessageChain,
                               app: GraiaMiraiApplication, group: Group,
                               member: Member):
    pinyinStr = ""
    for i in range(len(lazy_pinyin(message.asDisplay()))):
        pinyinStr += lazy_pinyin(message.asDisplay())[i]
    if not pinyinStr.startswith("/"):
        if pinyinStr.find("setu") >= 0:
            if member.id in BlackId:
                await app.sendGroupMessage(
                    group,
                    MessageChain.create(
                        [At(member.id), Plain("哼(╯▔皿▔)╯,不理你了!")]))
            else:
                if SearchSetting(group.id)["function"]["setu"]:
                    try:
                        url = "https://api.lolicon.app/setu/?apikey=" + LoliconKey[
                            0]  # 1号api
                        data = json.loads(await aioRequest(url))
                        if data['code'] == 0:
                            messageId = await app.sendGroupMessage(
                                group,
                                MessageChain.create([
                                    At(member.id),
                                    Image.fromNetworkAddress(
                                        data['data'][0]['url'])
                                ]))
                            await asyncio.sleep(60)
                            await app.revokeMessage(messageId)
                        elif data['code'] == 429:
                            url = "https://api.lolicon.app/setu/?apikey=" + LoliconKey[
                                1]  # 2号api
                            data = json.loads(await aioRequest(url))
                            if data['code'] == 0:
                                messageId = await app.sendGroupMessage(
                                    group,
                                    MessageChain.create([
                                        At(member.id),
                                        Image.fromNetworkAddress(
                                            data['data'][0]['url'])
                                    ]))
                                await asyncio.sleep(60)
                                await app.revokeMessage(messageId)
                            else:
                                await app.sendGroupMessage(
                                    group,
                                    MessageChain.create([
                                        At(member.id),
                                        Plain("今天发的已经够多了,明天再来吧~")
                                    ]))
                        else:
                            await app.sendGroupMessage(
                                group,
                                MessageChain.create(
                                    [At(member.id),
                                     Plain("今天发的已经够多了,明天再来吧~")]))
                    except:
                        await app.sendGroupMessage(
                            group,
                            MessageChain.create([
                                At(member.id),
                                Plain("诶呀,发生一个未知的错误(ˉ▽ˉ;)...")
                            ]))
                else:
                    await app.sendGroupMessage(
                        group,
                        MessageChain.create(
                            [At(member.id),
                             Plain("本群因管理要求已禁止使用色图功能╮(╯▽╰)╭")]))
Exemple #26
0
         if 'net_image' in msg:
             imglist.append(msg['net_image'])
         if 'net_audio' in msg:
             audlist.append(msg['net_audio'])
         if 'apilink' in msg:
             get_link = msg['apilink']
         if 'url' in msg:
             urllist.update({msg['url']: get_link})
     if status is None:
         msglist = msglist.plusWith(MessageChain.create([Plain('发生错误:机器人内部代码错误,请联系开发者解决。')]))
 if msglist != MessageChain.create([]):
     await sendMessage(kwargs, msglist)
     if imglist != []:
         imgchain = MessageChain.create([])
         for img in imglist:
             imgchain = imgchain.plusWith(MessageChain.create([Image.fromNetworkAddress(img)]))
         await sendMessage(kwargs, imgchain, Quote=False)
     if audlist != []:
         for aud in audlist:
             audchain = MessageChain.create(
                 [Voice().fromLocalFile(await slk_converter(await download_to_cache(aud)))])
             await sendMessage(kwargs, audchain, Quote=False)
 if urllist != {}:
     print(urllist)
     infoboxchain = MessageChain.create([])
     for url in urllist:
         get_infobox = await get_infobox_pic(urllist[url], url, headers)
         if get_infobox:
             infoboxchain = infoboxchain.plusWith(
                 MessageChain.create([Image.fromLocalFile(get_infobox)]))
     if infoboxchain != MessageChain.create([]):
Exemple #27
0
    async def process(messagePlain: str, group, member):
        """
        处理游戏进度
        :param messagePlain
        :param group
        :param member
        """
        global a, q
        if messagePlain == "exit":
            akinatorGame.hold = False
            akinatorGame.end = False

        if akinatorGame.end:  # 评价结果
            if messagePlain.lower() == "yes" or messagePlain.lower() == "y":
                await atri.app.sendGroupMessage(group, MessageChain.create(
                    [
                        Plain("Yay")
                    ]
                ))
            else:
                await atri.app.sendGroupMessage(group, MessageChain.create(
                    [
                        Plain("Oof")
                    ]
                ))
            akinatorGame.end = False
        if akinatorGame.hold and messagePlain in [
            'yes', 'y', '0',
            'no', 'n', '1',
            'i', 'idk', 'i dont know', "i don't know", '2',
            'probably', 'p', '3',
            'probably not', 'pn', '4'
        ]:  # 分支过程中
            a = messagePlain
            if a == "b":
                try:
                    q = akinatorGame.aki.back()
                    await atri.app.sendGroupMessage(group, MessageChain.create(
                        [
                            Plain(q)
                        ]
                    ))
                except akinator.CantGoBackAnyFurther:
                    pass
            else:
                q = akinatorGame.aki.answer(a)
                await atri.app.sendGroupMessage(group, MessageChain.create(
                    [
                        Plain(q + "\n\t"),
                        Plain(f"{akinatorGame.aki.progression}%")
                    ]
                ))

            if akinatorGame.aki.progression > 99:  # 给出结果
                akinatorGame.hold = False
                akinatorGame.aki.win()
                await atri.app.sendGroupMessage(group, MessageChain.create(
                    [
                        Plain(
                            f"It's {akinatorGame.aki.first_guess['name']} ({akinatorGame.aki.first_guess['description']})! Was I correct?\n"),
                        Image.fromNetworkAddress(akinatorGame.aki.first_guess['absolute_picture_path'])
                    ]
                ))
                akinatorGame.end = True

        if messagePlain in akinatorGame.AkinatorCmd and not akinatorGame.hold:  # start
            akinatorGame.end = False
            akinatorGame.hold = True
            await atri.app.sendGroupMessage(group, MessageChain.create(
                [
                    Plain("Please wait...\n"
                          '''yes or y or 0 for YES
no or n or 1 for NO
i or idk or i dont know or i don't know or 2 for I DON’T KNOW
probably or p or 3 for PROBABLY
probably not or pn or 4 for PROBABLY NOT'''
                          ),
                ]
            ))
            q = akinatorGame.aki.start_game("cn")
            await atri.app.sendGroupMessage(group, MessageChain.create(
                [
                    Plain(q + "\n\t"),
                    Plain(f"{akinatorGame.aki.progression}%")
                ]
            ))
Exemple #28
0
async def printDM(app, data, room_id):
    '''解析并输出数据包的数据'''
    # 如果传入的data为null则直接返回
    if not data:
        return

    # 获取数据包的长度,版本和操作类型
    packetLen = int(data[:4].hex(), 16)
    ver = int(data[6:8].hex(), 16)
    op = int(data[8:12].hex(), 16)

    # 有的时候可能会两个数据包连在一起发过来,所以利用前面的数据包长度判断,

    if (len(data) > packetLen):
        await printDM(app, data[packetLen:], room_id)
        data = data[:packetLen]

    # 有时会发送过来 zlib 压缩的数据包,这个时候要去解压。
    if (ver == 2):
        data = zlib.decompress(data[16:])
        await printDM(app, data, room_id)
        return

    # ver 为1的时候为进入房间后或心跳包服务器的回应。op 为3的时候为房间的人气值。
    if (ver == 1):
        if (op == 3):
            t = datetime.datetime.now().strftime("[%Y-%m-%d %H:%M:%S,%f")
            t = t[:len(t) - 3] + ']'
            print('%s[POPULARITY]: %s: %d' %
                  (t, room_id, int(data[16:].hex(), 16)))
        return

    # ver 不为2也不为1目前就只能是0了,也就是普通的 json 数据。
    # op 为5意味着这是通知消息,cmd 基本就那几个了。
    if (op == 5):
        jd = json.loads(data[16:].decode('utf-8', errors='ignore'))
        sstr = ''
        '''
        if(jd['cmd'] == 'DANMU_MSG'):
            sstr = '[DANMU] ' + jd['info'][2][1] + ': ' + jd['info'][1]
        elif(jd['cmd'] == 'LIVE'):
            sstr = '[Notice] LIVE Start!'
        elif(jd['cmd'] == 'PREPARING'):
            sstr = '[Notice] LIVE Ended!'
        elif(jd['cmd'] == 'SEND_GIFT'):
            sstr = '[GIFT]' + jd['data']['uname'] + ' ' + jd['data']['action'] + \
                ' ' + str(jd['data']['num']) + 'x' + jd['data']['giftName']
        elif(jd['cmd'] == "INTERACT_WORD"):
            if jd['data']['msg_type'] == 1:
                sstr = '[ENTRY] ' + jd['data']['uname'] + ' 进入直播间'
            elif jd['data']['msg_type'] == 2:
                sstr = '[FOLLOW] ' + jd['data']['uname'] + ' 关注了直播间'
        elif(jd['cmd'] == "未知"):
            print(jd)
            sstr = '[SHARE] ' + jd['data']['uname'] + ' 分享了直播间'
        else:
            sstr = '[OTHER] ' + jd['cmd']

        if sstr != '':
            await app.sendGroupMessage(group, MessageChain.create([Plain(sstr)]))
        '''

        if (jd['cmd'] != 'LIVE'):
            return
        Localpath = './data/live.json'
        data = {}
        fr = open(Localpath, encoding='utf-8')
        data = json.load(fr)
        fr.close()
        info = get_info(room_id)
        for i in data["data"]:
            if (room_id != str(i['room_id'])):
                continue
            for j in i['group']:
                sstr = '%s的直播开始啦!\n直播间标题:%s\n直播关键帧:' % (info['user'],
                                                        info['title'])
                await app.sendGroupMessage(
                    j,
                    MessageChain.create([
                        Plain(sstr),
                        Image.fromNetworkAddress(info['keyframe']),
                        Plain('\n直播间地址:https://live.bilibili.com/%d' %
                              info['room_id'])
                    ]))
            raise Exception("断开连接")
Exemple #29
0
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)
Exemple #30
0
async def blhx(app, group):
    url = "https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/space_history?visitor_uid=33091201&host_uid=233114659&offset_dynamic_id=0&need_top=1&platform=web"
    Information = requests.get(url, headers=headers).json()
    judge = Information['data']['cards'][1]

    if judge['desc']['type'] == 1:
        needInformation = Information['data']['cards'][1]['card']
        dictInformation = eval(needInformation)
        msg = dictInformation['item']['content']
        message = MessageChain.create(
            [Plain("碧蓝航线b服动态更新\n================\n"),
             Plain(msg)])
        await app.sendGroupMessage(group, message)

    elif judge['desc']['type'] == 2:
        needInformation = Information['data']['cards'][1]['card']
        dictInformation = eval(needInformation)
        try:
            if (dictInformation['item']['pictures_count'] == 1):
                pictures = dictInformation['item']['pictures'][0]['img_src']
                flag = 0
            else:
                pictures = dictInformation['item']['pictures']
                flag = 1
                count = dictInformation['item']['pictures_count']
        except:
            pictures = " "
        msgDict = {
            "information": dictInformation['item']['description'],
            "picture_url": pictures
        }
        if msgDict['picture_url'] != ' ':
            if flag == 0:
                msgDict['picture_url'] = eval(
                    repr(msgDict['picture_url']).replace('\\', ''))
                await app.sendGroupMessage(
                    group,
                    MessageChain.create([
                        Plain("碧蓝航线b服动态更新\n================\n"),
                        Plain(msgDict['information']),
                        Image.fromNetworkAddress(msgDict['picture_url'])
                    ]))
            elif flag == 1:
                message1 = MessageChain.create([
                    Plain("碧蓝航线b服动态更新\n================\n"),
                    Plain(msgDict['information'])
                ])
                for i in range(count):
                    msg = MessageChain.join(
                        [Image.fromNetworkAddress(pictures[i]['img_src'])])
                #Msg = MessageChain.join(message1, msg)
                #await app.sendGroupMessage(group, Msg)
        else:
            await app.sendGroupMessage(
                group,
                MessageChain.create([
                    Plain("碧蓝航线b服动态更新\n================\n"),
                    Plain(msgDict['information'])
                ]))

    elif judge['desc']['type'] == 4:
        needInformation = Information['data']['cards'][1]['card']
        dictInformation = eval(needInformation)
        pictures = " "
        msgDict = {
            "information": dictInformation['item']['content'],
            "picture_url": pictures
        }
        for group in groups:
            if msgDict['picture_url'] != ' ':
                msgDict['picture_url'] = eval(
                    repr(msgDict['picture_url']).replace('\\', ''))
                await app.sendGroupMessage(
                    group,
                    MessageChain.create([
                        Plain("碧蓝航线b服动态更新\n================\n"),
                        Plain(msgDict['information']),
                        Image.fromNetworkAddress(msgDict['picture_url'])
                    ]))
            else:
                await app.sendGroupMessage(
                    group,
                    MessageChain.create([
                        Plain("碧蓝航线b服动态更新\n================\n"),
                        Plain(msgDict['information'])
                    ]))