Пример #1
0
def rssSubscribe(session: CommandSession):
    rssLink: str = session.get("link")
    session.send(f'开始检查订阅源:"{rssLink}"')
    # Get feed data
    rssResource: str = downloadFeed(rssLink)
    rssResourceParse: dict = rssParser(rssResource)
    # Check for duplicates with existing subscriptions
    subscribeToken = rssResourceParse["token"]
    getSettings = PluginManager.settings(__plugin_name__, session.ctx).settings
    if getSettings["subscribed"].get(subscribeToken):
        raise BotExistError(reason="此订阅已存在!")
    else:
        getSettings["subscribed"][subscribeToken] = {
            "link": rssLink,
            "last_update": rssResourceParse["last_update_stamp"],
        }
    # Processing messages
    repeatMessage = "\n".join(
        [
            str(CONFIG.customize.subscribe_repeat).format(**i)
            for i in rssResourceParse["content"][: CONFIG.customize.size]
        ]
    )
    fullMessage = (
        str(CONFIG.customize.subscribe_prefix).format(**rssResourceParse)
        + f"{repeatMessage}\n"
        + str(CONFIG.customize.subscribe_suffix).format(**rssResourceParse)
    )
    PluginManager.settings(__plugin_name__, session.ctx).settings = getSettings
    return fullMessage
Пример #2
0
async def lssv(session: CommandSession):
    parser = ArgumentParser(session=session)
    parser.add_argument('-a', '--all', action='store_true')
    parser.add_argument('-H', '--hidden', action='store_true')
    parser.add_argument('-g', '--group', type=int, default=0)
    args = parser.parse_args(session.argv)

    verbose_all = args.all
    only_hidden = args.hidden
    if session.ctx['user_id'] in session.bot.config.SUPERUSERS:
        gid = args.group or session.ctx.get('group_id')
        if not gid:
            session.finish('Usage: -g|--group <group_id> [-a|--all]')
    else:
        gid = session.ctx['group_id']

    msg = [f"群{gid}服务一览:"]
    svs = Service.get_loaded_services().values()
    svs = map(lambda sv: (sv, sv.check_enabled(gid)), svs)
    key = cmp_to_key(lambda x, y: (y[1] - x[1]) or (-1 if x[0].name < y[
        0].name else 1 if x[0].name > y[0].name else 0))
    svs = sorted(svs, key=key)
    for sv, on in svs:
        if verbose_all or (sv.visible ^ only_hidden):
            x = '○' if on else '×'
            msg.append(f"|{x}| {sv.name}")
    await session.send('\n'.join(msg))
Пример #3
0
async def _(session: CommandSession):
    stripped_arg = session.current_arg_text.strip() # 删去首尾空白
    if stripped_arg:
        session.state['text'] = stripped_arg
    else:
        session.state['text'] = None
    return
Пример #4
0
def _(session: CommandSession):
    from re import search

    strippedArgs = session.current_arg_text.strip()
    matchObj = search(r"[a-fA-F0-9]{8,40}", strippedArgs)
    if not matchObj:
        session.pause("请输入激活密钥")
    session.state["key"] = str(matchObj.group(0)).upper()
Пример #5
0
async def switch_service(session: CommandSession, turn_on: bool):
    action_tip = '启用' if turn_on else '禁用'
    if session.ctx['message_type'] == 'group':
        names = session.current_arg_text.split()
        if not names:
            session.finish(f"空格后接要{action_tip}的服务名", at_sender=True)
        group_id = session.ctx['group_id']
        svs = Service.get_loaded_services()
        succ, notfound = [], []
        for name in names:
            if name in svs:
                sv = svs[name]
                u_priv = priv.get_user_priv(session.ctx)
                if u_priv >= sv.manage_priv:
                    sv.set_enable(group_id) if turn_on else sv.set_disable(
                        group_id)
                    succ.append(name)
                else:
                    try:
                        await session.send(
                            f'权限不足!{action_tip}{name}需要:{sv.manage_priv},您的:{u_priv}\n{PRIV_TIP}',
                            at_sender=True)
                    except:
                        pass
            else:
                notfound.append(util.escape(name))
        msg = []
        if succ:
            msg.append(f'已{action_tip}服务:' + ', '.join(succ))
        if notfound:
            msg.append('未找到服务:' + ', '.join(notfound))
        if msg:
            session.finish('\n'.join(msg), at_sender=True)

    else:
        if session.ctx['user_id'] not in session.bot.config.SUPERUSERS:
            return
        args = session.current_arg_text.split()
        if len(args) < 2:
            session.finish(
                'Usage: <service_name> <group_id1> [<group_id2>, ...]')
        name, *group_ids = args
        svs = Service.get_loaded_services()
        if name not in svs:
            session.finish(f'未找到服务:{name}')
        sv = svs[name]
        succ = []
        for gid in group_ids:
            try:
                gid = int(gid)
                sv.set_enable(gid) if turn_on else sv.set_disable(gid)
                succ.append(gid)
            except:
                try:
                    await session.send(f'非法群号:{gid}')
                except:
                    pass
        session.finish(f'服务{name}已于{len(succ)}个群内{action_tip}:{succ}')
Пример #6
0
def _(session: CommandSession):
    strippedArgs = session.current_arg_text.strip()
    if not strippedArgs:
        session.pause("请输入画师的用户ID")
    numberArgs = extract_numbers(session.current_arg_text)
    if len(numberArgs) > 2:
        session.pause("您输入的参数不正确")
    page, member = numberArgs if len(numberArgs) == 2 else (1, numberArgs[0])
    session.state["page"], session.state["id"] = int(page), int(member)
Пример #7
0
def _(session: CommandSession):
    strippedArgs = session.current_arg_text.strip()
    numberArgs = extract_numbers(strippedArgs)
    avaliableRank = "".join(
        set(i for i in strippedArgs if i.upper() in ["S", "Q", "E"])
    )
    if avaliableRank:
        session.state["rank"] = avaliableRank
    if numberArgs:
        session.state["num"] = int(numberArgs[0])
Пример #8
0
def _(session: CommandSession):
    banID = extract_numbers(session.current_arg_text)
    if not banID:
        session.pause("请输入被洗白者的QQ")
    nowBlacklist: list = PluginManager.settings(__plugin_name__,
                                                session.event).settings
    nowBlacklist = [i for i in nowBlacklist if i not in banID]
    PluginManager.settings(__plugin_name__,
                           session.event).settings = [*set(nowBlacklist)]
    return "已经为" + "".join(map(lambda x: str(MessageSegment.at(x)),
                               banID)) + "移除黑名单"
Пример #9
0
def _(session: CommandSession):
    if session.state.get("id", None):
        return
    args = session.current_arg_text.strip()
    avResult = MATCH_AV.search(args)
    bvResult = MATCH_BV.search(args)
    if avResult:
        session.state["id"] = int(avResult.group(1))
    elif bvResult:
        session.state["id"] = IDCoverter.bv2av(bvResult.group())
    else:
        session.pause("请输入正确的bv号或者av号")
Пример #10
0
def illustSearch(session: CommandSession):
    imageURL = session.get("image")
    session.send("开始以图搜图")
    searchContent = searchImage(imageURL)
    searchParse = getCorrectInfo(searchContent)
    messageRepeat = [
        str(Config.customize.repeat).format(**subject)
        for subject in searchParse["subject"]
    ]
    fullMessage = (str(Config.customize.prefix).format(**searchParse) +
                   "".join(messageRepeat[:Config.customize.size]) +
                   str(Config.customize.suffix).format(**searchParse))
    return fullMessage
Пример #11
0
def enableR18(session: CommandSession):
    key = session.get("key")
    settings = PluginManager.settings(OPERATING_METHOD, ctx=session.ctx)
    if str(settings.settings.get("key", "")).upper() != str(key).upper():
        session.finish(f"密钥{key}无法激活该功能")
    PluginManager.settings(MEMBER_IMAGE_METHOD, ctx=session.ctx).settings = {
        "r-18": True
    }
    PluginManager.settings(SEARCH_IMAGE_METHOD, ctx=session.ctx).settings = {
        "r-18": True
    }
    PluginManager.settings(GET_IMAGE_METHOD, ctx=session.ctx).settings = {"r-18": True}
    return "封印已成功解除", False
Пример #12
0
def _(session: CommandSession):
    numberArgs = extract_numbers(session.current_arg_text)
    textArgs = extract_text(session.current_arg_text)
    if not numberArgs:
        session.pause("请输入p站图片ID")
    session.state["id"] = int(numberArgs[0])
    keywordChoice = {
        "大图": "large",
        "小图": "medium",
        "原图": "original",
    }
    for key, value in keywordChoice.items():
        if key in textArgs:
            session.state["res"] = value
            break
Пример #13
0
def _(session: CommandSession):
    session.send("开始生成词云")
    latestTime = datetime.datetime.now() - DELTA_TIME
    if "group_id" in session.ctx:
        messageIter = messageGenterator(group_id=session.ctx["group_id"],
                                        latestTime=latestTime)
    else:
        messageIter = messageGenterator(user_id=session.ctx["user_id"],
                                        latestTime=latestTime)
    wordcloud = WordcloudMaker()
    for data in messageIter:
        data: models.RecordsRead
        sentence = data.content
        wordcloud.update(sentence)
    imageData = wordcloud.save()
    return MessageSegment.image(f"base64://{b64encode(imageData).decode()}")
Пример #14
0
async def translate(session: CommandSession):
    text = session.get('text')
    if text:
        translation = await get_translation(text)
        await session.send(f'机翻译文:\n{translation}')
    else:
        await session.send('翻译姬待命中...')
Пример #15
0
def _(session: CommandSession):
    session.send("开始获取一图")
    randomRank = random.choice(["day", "week", "month"])
    apiParse = parseMultiImage(pixiv.getRank(randomRank))
    choiceResult = random.choice(
        [data for data in apiParse["result"] if data["type"] == "illust"]
    )
    imageLinks = [i["large"] for i in choiceResult["download"]][: Config.customize.size]
    images = downloadMutliImage(imageLinks)
    messageRepeat = [str(MessageSegment.image(images[i])) for i in imageLinks]
    fullMessage = (
        str(Config.customize.rank_prefix).format(**choiceResult)
        + "\n".join(messageRepeat)
        + "\n"
        + str(Config.customize.rank_suffix).format(**choiceResult)
    )
    return fullMessage
Пример #16
0
def _(session: CommandSession):
    banID = extract_numbers(session.current_arg_text)
    groupUsers = [
        i["user_id"]
        for i in callModuleAPI("get_group_member_list",
                               params={"group_id": session.event.group_id})
    ]
    banID = [*set([int(i) for i in banID]).intersection({*groupUsers})]
    if not banID:
        session.pause("请输入被拉黑者的QQ")
    nowBlacklist: list = PluginManager.settings(__plugin_name__,
                                                session.event).settings
    nowBlacklist.extend(map(int, banID))
    PluginManager.settings(__plugin_name__,
                           session.event).settings = [*set(nowBlacklist)]
    return "已经为" + "".join(map(lambda x: str(MessageSegment.at(x)),
                               banID)) + "添加黑名单"
Пример #17
0
def NSFWImage(session: CommandSession):
    rank: str = session.get_optional("rank", Config.send.default)
    pictureCount: int = session.get_optional("num", 1)
    pictureCount = (
        pictureCount if pictureCount <= Config.send.size else Config.send.size
    )
    session.send(f"{rank.upper()}级涩图加载中,将发送最多{pictureCount}张")
    imageInfoList: List[Dict[str, Any]] = getImageList()
    imageList: List[str] = [
        i.get("sample_url", i.get("file_url"))
        for i in imageInfoList
        if i["rating"].upper() in rank.upper()
    ]
    random.shuffle(imageList)
    images = downloadMultiImage([i for i in imageList if i][:pictureCount])
    imageSent = [str(MessageSegment.image(i)) for i in images.values()]
    return "\n".join(imageSent) + f"\n共筛选出{len(imageList)}张图片"
Пример #18
0
def broadcast(session: CommandSession):
    broadcastContent = session.get("content")
    session.send(f"开始广播消息,内容如下:\n{broadcastContent}")
    beginTime = time()
    groupsList: List[int] = [
        i["group_id"] for i in callModuleAPI("get_group_list")
    ]
    totalSend = 0
    for groupID in groupsList:
        enabled = PluginManager._getSettings(__plugin_name__,
                                             type="group",
                                             id=groupID).status
        if not enabled:
            continue
        sendParams = {"group_id": groupID, "message": broadcastContent}
        callModuleAPI("send_msg", params=sendParams, ignoreError=True)
        totalSend += 1
    return f"消息广播完成,已广播到{totalSend}个群聊\n耗时{time() - beginTime:.3f}s"
Пример #19
0
def repeatSetter(session: CommandSession):
    getSettings = PluginManager.settings(__plugin_name__, ctx=session.ctx)
    getRate = session.get_optional("rate", False)
    getRate = getRate if getRate else getSettings.settings["rate"]
    groupID = session.ctx["group_id"]
    if not getSettings.status:
        getSettings.status = True
    getSettings.settings = {"rate": getRate}
    return f"群{groupID}复读概率已被设置为{1/getRate:.3%}"
Пример #20
0
def catch(session: CommandSession):
    stackID: str = session.get("id")
    returnData = """
    追踪ID:{stack_id}
    出错时间:{time_format}(时间戳{time})
    错误堆栈:\n{stack}""".format(
        **ExceptionProcess.read(stackID.upper())
    )
    return returnData
Пример #21
0
def memberImage(session: CommandSession):
    memberID = session.get("id")
    enableR18 = PluginManager.settings(MEMBER_IMAGE_METHOD, session.ctx).settings[
        "r-18"
    ]
    page = session.get_optional("page", 1)
    session.send(f"开始获取Pixiv用户ID为{memberID}的作品第{page}页")
    apiGet = pixiv.getMemberIllust(memberID, page)
    apiParse = parseMultiImage(apiGet, mosaicR18=not enableR18)
    sortResult = sorted(apiParse["result"], key=lambda x: x["ratio"], reverse=True)
    messageRepeat = [
        str(Config.customize.member_repeat).format(**data) for data in sortResult
    ]
    fullMessage = (
        str(Config.customize.member_prefix).format(**apiParse)
        + "".join(messageRepeat[: Config.customize.size])
        + str(Config.customize.member_suffix).format(**apiParse)
    )
    return fullMessage
Пример #22
0
def searchImage(session: CommandSession):
    enableR18 = PluginManager.settings(SEARCH_IMAGE_METHOD, session.ctx).settings[
        "r-18"
    ]
    keywords = session.get("keyword")
    page = session.get_optional("page", 1)
    session.send(f'开始搜索"{keywords}"的第{page}页')
    apiGet = pixiv.searchIllust(keyword=keywords, page=page)
    apiParse = parseMultiImage(apiGet, mosaicR18=not enableR18)
    sortResult = sorted(apiParse["result"], key=lambda x: x["ratio"], reverse=True)
    messageRepeat = [
        str(Config.customize.search_repeat).format(**data) for data in sortResult
    ]
    fullMessage = (
        str(Config.customize.search_prefix).format(**apiParse)
        + "".join(messageRepeat[: Config.customize.size])
        + str(Config.customize.search_suffix).format(**apiParse)
    )
    return fullMessage
Пример #23
0
def animeSearch(session: CommandSession):
    imageLink = session.get("image")
    session.send("开始以图搜番")
    imageRes = imageDownload(imageLink)
    if determineImageType(imageRes) == "GIF":
        session.send("检测到GIF图片格式,自动截取第一帧上传")
        imageRes = processGIF(imageRes)
    if len(imageRes) >= 1024**2:
        raise BotProgramError("图片大小超过限制,必须小于1MiB," +
                              f"您的图片大小为{len(imageRes)/1024**2:.3f}MiB")
    searchResult = whatanimeUpload(imageRes)
    messageRepeat = [
        str(Config.customize.repeat).format(**perAnime)
        for perAnime in searchResult["docs"]
    ]
    fullMessage = (str(Config.customize.prefix).format(**searchResult) +
                   "".join(messageRepeat[:Config.customize.size]) +
                   str(Config.customize.suffix).format(**searchResult))
    return fullMessage
Пример #24
0
def _(session: CommandSession):
    session.send("开始生成统计")
    latestTime = datetime.datetime.now() - DELTA_TIME
    newestTime = _datetimeRound(datetime.datetime.now())
    frameMaker = DataFrameMaker({"date": str, "time": float})
    if "group_id" in session.ctx:
        messageIter = messageGenterator(
            group_id=session.ctx["group_id"],
            newestTime=newestTime,
            latestTime=latestTime,
        )
    else:
        messageIter = messageGenterator(user_id=session.ctx["user_id"],
                                        newestTime=newestTime,
                                        latestTime=latestTime)
    for data in messageIter:
        date = str(data.time.date())
        time = _time2Int(data.time.time())
        frameMaker.update({"date": date, "time": time})
    imageData = Chart.chatFrequency(frameMaker.read())
    return MessageSegment.image(f"base64://{b64encode(imageData).decode()}")
Пример #25
0
def enable(session: CommandSession):
    key: str = session.get("key")
    realKey: str = PluginManager.settings(
        pluginName=OPERATING_METHOD, ctx=session.ctx
    ).settings.get("key", "")
    if key.upper() == realKey.upper():
        PluginManager.settings(
            pluginName=__plugin_name__, ctx=session.ctx
        ).status = True
        return "涩图功能已启用", False
    else:
        return "此激活密钥无效", False
Пример #26
0
def wikipedia(session: CommandSession):
    keyword = session.get("keyword")
    session.send(f"开始Wiki搜索:{keyword}")
    pages = getWiki(keyword)["query"]["pages"]
    finalResult = {"keyword": keyword, "size": len(pages)}
    finalResult["result"] = []
    for page in pages.values():
        finalResult["result"].append({
            "title":
            page["title"],
            "introduce":
            page["extract"],
            "link":
            NetworkUtils.shortLink([page["fullurl"]])[page["fullurl"]],
        })
    repeatMessage = [
        str(CONFIG_READ.customize.repeat).format(**result)
        for result in finalResult["result"]
    ]
    fullMessage = (str(CONFIG_READ.customize.prefix).format(**finalResult) +
                   "".join(repeatMessage[:CONFIG_READ.size]) +
                   str(CONFIG_READ.customize.suffix).format(**finalResult))
    return fullMessage
Пример #27
0
def getImage(session: CommandSession):
    allowR18: bool = PluginManager.settings(GET_IMAGE_METHOD, ctx=session.ctx).settings[
        "r-18"
    ]
    imageID: int = session.get("id")
    imageResloution: str = session.get_optional("res", "large")
    session.send(f"开始获取Pixiv ID为{imageID}的{imageResloution}")
    apiGet = pixiv.getImageDetail(imageID)
    apiParse = parseSingleImage(apiGet, mosaicR18=not allowR18)
    imageURLs = [p[imageResloution] for p in apiParse["download"]][
        : Config.customize.size
    ]
    imageDownloaded = downloadMutliImage(
        imageURLs, mosaic=((not allowR18) and apiParse["r-18"])
    )
    images = [str(MessageSegment.image(imageDownloaded[i])) for i in imageURLs]
    repeatMessage = "\n".join(images)
    finalMessage = (
        str(Config.customize.image_prefix).format(**apiParse)
        + f"{repeatMessage}\n"
        + str(Config.customize.image_suffix).format(**apiParse)
    )
    return finalMessage
Пример #28
0
def _(session: CommandSession):
    if session.current_arg_images:
        session.switch(f"!{GET_IMAGE_METHOD} {session.current_arg}")
    strippedArgs = session.current_arg_text.strip()
    if not strippedArgs:
        session.pause("请输入搜索关键词")
    keywords: List[str] = strippedArgs.split(" ")
    if len(keywords) >= 2:
        if keywords[0].isdigit():
            session.state["page"] = int(keywords[0])
            keywords.pop(0)
    session.state["keyword"] = " ".join(keywords)
Пример #29
0
def _(session: CommandSession):
    strippedArgs = session.current_arg_text.strip()
    if not strippedArgs:
        session.pause("请输入错误追踪ID")
    session.state["id"] = strippedArgs
Пример #30
0
def _(session: CommandSession):
    strippedArgs = session.current_arg_text.strip()
    if not strippedArgs:
        session.pause("请输入搜索关键词")
    session.state["keyword"] = strippedArgs