Exemplo n.º 1
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.º 2
0
 def wrapper(*args, **kwargs):
     global _MODIFED, _CACHE
     if _MODIFED:
         if _CACHE:
             _SettingsIO.write(_CACHE)
         _CACHE = _SettingsIO.read()
         logger.debug(f"Plugin configuration has been updated:{_CACHE}")
         _MODIFED = False
     return function(*args, **kwargs)
Exemplo n.º 3
0
def _(session: NLPSession):
    message = htmlUnescape(str(session.event.message))
    searchResult = MATCH_RICH_TEXT.search(message)
    if not searchResult:
        return
    logger.debug(f"Catch miniprogram {searchResult}")
    return IntentCommand(100,
                         name="miniprogram_extract",
                         args={"data": searchResult.group(1)})
Exemplo n.º 4
0
 def wrapper(*args, **kwargs):
     functionName = _getFunctionName(function)
     startTime = time() * 1000
     try:
         return function(*args, **kwargs)
     finally:
         runningCost = (time() * 1000) - startTime
         logger.debug(
             f"Function {functionName} cost {runningCost:.3f}ms." +
             f"args={str(args):.100s}...,kwargs={str(kwargs):.100s}...")
Exemplo n.º 5
0
 def wrapper(*args, **kwargs):
     for _ in range(retries if retries else 1):
         try:
             return function(*args, **kwargs)
         except RequestException as error:
             traceID = ExceptionProcess.catch()
             logger.debug(f"Function {functionName} encountered" +
                          f'a network request error: "{error}"')
             if isinstance(error, HTTPError):
                 break
     raise BotRequestError(prompt, traceID)
Exemplo n.º 6
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.º 7
0
    def __call__(
        self,
        pluginName: str,
        defaultStatus: Optional[bool] = True,
        defaultSettings: Optional[Any] = {},
    ):
        """Register a plugin

        Parameters
        ----------
        pluginName : str
            Plugin name
        defaultStatus : Optional[bool], optional
            Enabled by default, by default True
        defaultSettings : Optional[Any], optional
            Empty by default, by default {}
        """
        global _MODIFED, _CACHE
        if _CACHE.get(pluginName):
            inCacheDefault = _CACHE[pluginName]["settings"]["default"]
            inCacheSetting = _CACHE[pluginName]["status"]["default"]
            if inCacheDefault == defaultSettings and inCacheSetting == defaultStatus:
                return
        _MODIFED = True
        _CACHE.update(
            {
                pluginName: {
                    "settings": {"group": {}, "user": {}, "default": defaultSettings},
                    "status": {"group": {}, "user": {}, "default": defaultStatus},
                }
            }
        )
        logger.debug(
            f"Register a new plugin:{pluginName},"
            + f"settings={defaultSettings},status={defaultStatus}"
        )
Exemplo n.º 8
0
from utils.objects import callModuleAPI, convertImageFormat
from utils.tmpFile import tmpFile

__plugin_name__ = "time_reminder"

PluginManager.registerPlugin(__plugin_name__)
POWER_GROUP = GROUP_ADMIN | SUPERUSER
CONFIG_DIR = "./configs/greeting.yml"
DEFAULT_DIR = "./configs/default.greeting.yml"
_IMAGE_LIST_CACHE = None

if not isfile(CONFIG_DIR):
    copyFileInText(DEFAULT_DIR, CONFIG_DIR)
CONFIG = configsReader(CONFIG_DIR, DEFAULT_DIR)

logger.debug(f"Apscheduler status: {apscheduler.version_info}.")


def resizeImage(image: bytes,
                *,
                height: Optional[int] = None,
                width: Optional[int] = None) -> bytes:
    with tmpFile() as tmpFileName:
        with open(tmpFileName, "wb") as f:
            f.write(image)
        with Image.open(tmpFileName) as img:
            originWidth, originHeight = img.size
            if height:
                width = int(originWidth * (height / originHeight))
            elif width:
                height = int(originHeight * (width / originWidth))
Exemplo n.º 9
0
def _(session: CommandSession):
    data = session.state["data"]
    parsed = parse(data)
    logger.debug(f"Parsed miniprogram {parsed}")
    return REPLY_FORMAT.format(**parsed)