Exemplo n.º 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
Exemplo n.º 2
0
def r18KeyBack(session: CommandSession):
    oldKey = PluginManager.settings(OPERATING_METHOD, ctx=session.ctx).settings.get(
        "key", token_hex(8)
    )
    key = "".join([chr(ord(i) + 10) for i in list(oldKey)])
    PluginManager.settings(OPERATING_METHOD, ctx=session.ctx).settings = {"key": key}
    return "分发的密钥已被收回"
Exemplo n.º 3
0
def _(session: CommandSession):
    getKey = PluginManager.settings(
        pluginName=OPERATING_METHOD, ctx=session.ctx
    ).settings.get("key", token_hex(8).upper())
    key = "".join([chr(ord(i) + 10) for i in list(getKey)])
    PluginManager.settings(pluginName=OPERATING_METHOD, ctx=session.ctx).settings = {
        "key": key
    }
    return "涩图密钥已被回收"
Exemplo n.º 4
0
def disableR18(session: CommandSession):
    PluginManager.settings(MEMBER_IMAGE_METHOD, ctx=session.ctx).settings = {
        "r-18": False
    }
    PluginManager.settings(SEARCH_IMAGE_METHOD, ctx=session.ctx).settings = {
        "r-18": False
    }
    PluginManager.settings(GET_IMAGE_METHOD, ctx=session.ctx).settings = {"r-18": False}
    return "强大的力量已被封印", False
Exemplo n.º 5
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)) + "移除黑名单"
Exemplo n.º 6
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
Exemplo n.º 7
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
Exemplo n.º 8
0
def batchSend():
    global _IMAGE_LIST_CACHE
    _IMAGE_LIST_CACHE = None
    logger.debug("Begin to start daily greeting")
    groupsList = [i["group_id"] for i in callModuleAPI("get_group_list")]
    successSend = 0
    for groupID in groupsList:

        enabled = PluginManager._getSettings(__plugin_name__,
                                             type="group",
                                             id=groupID).status
        if not enabled:
            continue
        try:
            callModuleAPI(
                "send_msg",
                params={
                    "group_id": groupID,
                    "message": timeTelling()
                },
            )
        except Exception:
            eid = ExceptionProcess.catch()
            logger.exception(
                f"Failed to greeting in group {groupID},traceback id:{eid}")
        else:
            successSend += 1
    logger.info(
        f"Daily greeting finished,total send:{len(groupsList)},success:{successSend}"
    )
Exemplo n.º 9
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)) + "添加黑名单"
Exemplo n.º 10
0
async def _(bot: NoneBot, event: Event, _):
    if event.user_id in settings.SUPERUSERS:
        return
    if "group_id" not in event:
        return
    blacklists = PluginManager.settings(__plugin_name__, event).settings
    if event.user_id in blacklists:
        raise CanceledException(f"User {event.user_id} is in blacklist")
Exemplo n.º 11
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%}"
Exemplo n.º 12
0
def _(session: NLPSession):
    groupRate = PluginManager.settings(__plugin_name__,
                                       ctx=session.ctx).settings["rate"]
    randomNum, msgID = randint(0, groupRate - 1), session.ctx["message_id"]
    groupID = session.ctx.get("group_id")
    if not groupID:
        return
    logger.debug(
        f"Chat {groupID} has a repeat probability of {1/groupRate:.3%}." +
        f"The random number of the current session {msgID} is {randomNum}.")
    if not randomNum:
        return session.msg, False
Exemplo n.º 13
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"
Exemplo n.º 14
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
Exemplo n.º 15
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
Exemplo n.º 16
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
Exemplo n.º 17
0
def _(session: NLPSession):
    status = PluginManager.settings(__plugin_name__, session.ctx).status
    if not status:
        return
    avResult = MATCH_AV.search(session.msg)
    bvResult = MATCH_BV.search(session.msg)
    if avResult:
        return IntentCommand(100,
                             name="bilibili_info",
                             args={
                                 "id": int(avResult.group(1)),
                                 "auto": True
                             })
    elif bvResult:
        return IntentCommand(
            100,
            name="bilibili_info",
            args={
                "id": IDCoverter.bv2av(bvResult.group()),
                "auto": True
            },
        )
    else:
        return
Exemplo n.º 18
0
from utils.decorators import SyncToAsync
from utils.manager import PluginManager
from utils.message import processSession

from .config import CONFIG
from .parse import BiliParser, IDCoverter, getVideoInfo

REPLY_FORMAT = CONFIG.customize.video
POWER_GROUP = SUPERUSER | GROUP_ADMIN
MATCH_AV = compileRegexp(CONFIG.customize.regexp.av)
MATCH_BV = compileRegexp(CONFIG.customize.regexp.bv)

__plugin_name__ = "bilibili"

PluginManager(__plugin_name__)


@on_command("bilibili_info", aliases=("视频信息", "b站视频"))
@processSession(pluginName=__plugin_name__)
@SyncToAsync
def vidInfo(session: CommandSession):
    aid = session.state["id"]
    responseData = getVideoInfo(aid)
    try:
        parsedData = BiliParser.parse(responseData)
    except Exception:
        if session.state.get("auto", False):
            return
        else:
            raise
Exemplo n.º 19
0
import os

import requests
from nonebot import CommandSession, on_command

from utils.configsReader import configsReader, copyFileInText
from utils.decorators import CatchRequestsException, SyncToAsync
from utils.message import processSession
from utils.network import NetworkUtils
from utils.manager import PluginManager

__plugin_name__ = "wikipedia"

PluginManager.registerPlugin(__plugin_name__)

CONFIG_PATH = "configs/wikipedia.yml"
DEFAULT_PATH = "configs/default.wikipedia.yml"

if not os.path.isfile(CONFIG_PATH):
    copyFileInText(DEFAULT_PATH, CONFIG_PATH)

CONFIG_READ = Config = configsReader(CONFIG_PATH, DEFAULT_PATH)


@CatchRequestsException(prompt="从维基获取数据出错")
def getWiki(keyword: str) -> dict:
    requestParam = {
        "action": "query",
        "generator": "prefixsearch",
        "gpssearch": keyword,
        "format": "json",
Exemplo n.º 20
0
def _(session: CommandSession):
    PluginManager.settings(__plugin_name__, session.ctx).status = True
    return "每日问好已启用"
Exemplo n.º 21
0
def _(session: CommandSession):
    nowBlacklist: list = PluginManager.settings(__plugin_name__,
                                                session.event).settings
    return ("目前" +
            "".join(map(lambda x: str(MessageSegment.at(x)), nowBlacklist)) +
            "在黑名单上")
Exemplo n.º 22
0
def _(session: CommandSession):
    PluginManager.settings(pluginName=__plugin_name__, ctx=session.ctx).status = False
    return "涩图功能已禁用"
Exemplo n.º 23
0
from random import randint

from nonebot import CommandSession, NLPSession, logger, on_command, on_natural_language
from nonebot.permission import GROUP_ADMIN, GROUP_MEMBER, SUPERUSER

from utils.decorators import SyncToAsync
from utils.message import processSession
from utils.objects import SyncWrapper
from utils.manager import PluginManager

__plugin_name__ = "repeater"

PluginManager.registerPlugin(__plugin_name__,
                             defaultStatus=True,
                             defaultSettings={"rate": 20})


@on_natural_language(permission=GROUP_MEMBER, only_to_me=False)
@processSession(pluginName=__plugin_name__)
@SyncToAsync
def _(session: NLPSession):
    groupRate = PluginManager.settings(__plugin_name__,
                                       ctx=session.ctx).settings["rate"]
    randomNum, msgID = randint(0, groupRate - 1), session.ctx["message_id"]
    groupID = session.ctx.get("group_id")
    if not groupID:
        return
    logger.debug(
        f"Chat {groupID} has a repeat probability of {1/groupRate:.3%}." +
        f"The random number of the current session {msgID} is {randomNum}.")
    if not randomNum:
Exemplo n.º 24
0
from utils.message import processSession

from .config import Config
from .parse import parseMultiImage, parseSingleImage
from .tools import cache, downloadMutliImage, pixiv

__plugin_name__ = "pixiv"

GET_IMAGE_METHOD = nameJoin(__plugin_name__, "get")
SEARCH_IMAGE_METHOD = nameJoin(__plugin_name__, "search")
MEMBER_IMAGE_METHOD = nameJoin(__plugin_name__, "member")
RANK_IMAGE_METHOD = nameJoin(__plugin_name__, "rank")
OPERATING_METHOD = nameJoin(__plugin_name__, "ops")
POWER_GROUP = GROUP_ADMIN | SUPERUSER | PRIVATE_FRIEND

PluginManager.registerPlugin(GET_IMAGE_METHOD, defaultSettings={"r-18": False})
PluginManager.registerPlugin(SEARCH_IMAGE_METHOD, defaultSettings={"r-18": False})
PluginManager.registerPlugin(MEMBER_IMAGE_METHOD, defaultSettings={"r-18": False})
PluginManager.registerPlugin(RANK_IMAGE_METHOD)
PluginManager.registerPlugin(OPERATING_METHOD)

_RANK_CACHE = {}


@on_command(GET_IMAGE_METHOD, aliases=("点图", "获取图片"))
@processSession(pluginName=GET_IMAGE_METHOD)
@WithKeyword("p站点图", command=GET_IMAGE_METHOD)
@SyncToAsync
def getImage(session: CommandSession):
    allowR18: bool = PluginManager.settings(GET_IMAGE_METHOD, ctx=session.ctx).settings[
        "r-18"
Exemplo n.º 25
0
def _(session: CommandSession):
    key = token_hex(8).upper()
    PluginManager.settings(pluginName=OPERATING_METHOD, ctx=session.ctx).settings = {
        "key": key
    }
    return f"涩图密钥已经生成,为{key}"
Exemplo n.º 26
0
from nonebot import CommandSession, MessageSegment, on_command
from nonebot.command.argfilter.extractors import extract_numbers
from nonebot.permission import GROUP_ADMIN, PRIVATE_FRIEND, SUPERUSER

from utils.decorators import SyncToAsync, WithKeyword
from utils.manager import PluginManager, nameJoin
from utils.message import processSession

from .config import Config
from .network import downloadMultiImage, getImageList

__plugin_name__ = "NSFWImages"
OPERATING_METHOD = nameJoin(__plugin_name__, "ops")
POWER_GROUP = GROUP_ADMIN | PRIVATE_FRIEND | SUPERUSER

PluginManager.registerPlugin(__plugin_name__, defaultStatus=False)
PluginManager.registerPlugin(OPERATING_METHOD)


@on_command(__plugin_name__, aliases=("setu", "涩图", "色图"))
@processSession(pluginName=__plugin_name__)
@WithKeyword("来一张涩图", command=__plugin_name__)
@SyncToAsync
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()
Exemplo n.º 27
0
from re import compile as compileRegexp

from nonebot import CommandSession, on_command, scheduler
from nonebot.permission import GROUP_ADMIN, PRIVATE_FRIEND, SUPERUSER

from utils.decorators import SyncToAsync
from utils.exception import BotExistError
from utils.manager import PluginManager, nameJoin
from utils.message import processSession

from .config import CONFIG, __plugin_name__
from .network import RefreshFeed, downloadFeed
from .parse import rssParser

PluginManager(__plugin_name__, defaultSettings={"subscribed": {}})
SUBSCRIBE_COMMAND = nameJoin(__plugin_name__, "subscribe")
TEST_COMMAND = nameJoin(__plugin_name__, "test")

URL_MATCH_REGEX = compileRegexp(
    r"(https?|ftp)://((?:\w|\d|[-+&@#/%?=~_|!:,.;])+(?:\w|\d|[-+&@#/%=~_|]))")
REFRESH_FEED = RefreshFeed()
POWER_GROUP = GROUP_ADMIN | PRIVATE_FRIEND | SUPERUSER


@on_command(SUBSCRIBE_COMMAND,
            aliases=("rss订阅", "RSS订阅"),
            permission=POWER_GROUP)
@processSession
@SyncToAsync
def rssSubscribe(session: CommandSession):
    rssLink: str = session.get("link")
Exemplo n.º 28
0
def r18KeyGen(session: CommandSession):
    key = token_hex(8).upper()
    PluginManager.settings(OPERATING_METHOD, ctx=session.ctx).settings = {"key": key}
    return f"密钥生成完毕,为{key}"
Exemplo n.º 29
0
def _(session: CommandSession):
    PluginManager.settings(__plugin_name__, session.ctx).status = False
    return "视频信息捕捉已关闭"
Exemplo n.º 30
0
def _(session: CommandSession):
    session: CommandSession = SyncWrapper(session)
    groupID = session.ctx["group_id"]
    getSettings = PluginManager.settings(__plugin_name__, ctx=session.ctx)
    getSettings.status = False
    session.send(f"群{groupID}复读已经关闭")