Пример #1
0
def callModuleAPI(
    method: str,
    params: Optional[dict] = {},
    ignoreError: Optional[bool] = False
) -> Optional[Union[Dict[str, Any], List[Dict[str, Any]]]]:
    """Call CQHTTP's underlying API

    Parameters
    ----------
    method : str
        The name of the method to call
    params : Optional[dict], optional
        Additional parameters for the call, by default {}

    Returns
    -------
    Callable
        The function that called the method
    """
    from .decorators import AsyncToSync

    botObject: NoneBot = get_bot()
    syncAPIMethod = AsyncToSync(botObject.call_action)
    logger.debug("CQHTTP native API is being actively called, " +
                 f"data: action={method}, params={str(params):.100s}")
    try:
        return syncAPIMethod(method, **(params or {}))
    except ActionFailed as e:
        if ignoreError:
            return
        from .exception import BotMessageError, ExceptionProcess

        raise BotMessageError(reason=f"调用API出错,错误:{e}",
                              trace=ExceptionProcess.catch())
Пример #2
0
    def store(cls, exceptionTime: float, exceptionStack: str) -> str:
        """Store a caught exception

        Parameters
        ----------
        exceptionTime : float
            Timestamp when the exception occurred
        exceptionStack : str
            Exception stack

        Returns
        -------
        str
            Unique ID used to identify the exception
        """
        stackID: str = token_hex(4).upper()
        storeDir: str = cls._getRecursivePath(f"{stackID}.json", makeDir=True)
        exceptionInfo: dict = {
            "stack_id": stackID,
            "time": exceptionTime,
            "time_format": time.strftime("%c %z",
                                         time.localtime(exceptionTime)),
            "stack": exceptionStack,
        }
        with open(storeDir, "wt", encoding="utf-8") as f:
            f.write(
                json.dumps(exceptionInfo,
                           ensure_ascii=False,
                           indent=4,
                           sort_keys=True))
        logger.debug(f"Has been saved Error Stack file {storeDir}, " +
                     f"content:{exceptionInfo}")
        return stackID
Пример #3
0
 async def wrapper():
     while True:
         await asyncio.sleep(1)
         try:
             info = await get_bot().call_action("get_login_info")
         except CQHttpError:
             pass
         else:
             break
     logger.debug(f"Program API started successfully, account info: {info}")
     await saveDetail()
Пример #4
0
def recordChat(session: NLPSession):
    content = extract_text(session.ctx["message"])
    ctx = session.ctx.copy()
    sender = session.ctx["user_id"]
    group = session.ctx.get("group_id")
    data = models.RecordsCreate(sender=sender,
                                group=group,
                                content=content,
                                ctx=ctx)

    try:
        result = DatabaseIO.recordCreate(data)
    except Exception as e:
        traceID = ExceptionProcess.catch()
        logger.warning(
            f"Chat record {data} failed to storage due to {e} (Traceback ID:{traceID})."
        )
    else:
        logger.debug(
            f"Chat record {result} has been storaged to database successfully."
        )
Пример #5
0
def rssParser(feed: str) -> dict:
    """Functions for handling RSS pushes

    Parameters
    ----------
    feed : str
        Downloaded RSS file content

    Returns
    -------
    dict
        A dictionary containing RSS information

    Raises
    ------
    BotProgramError
        Thrown when RSS processing fails
    """

    try:
        parsedData: FeedParserDict = parseFeed(feed)
        if parsedData.get("bozo") != 0:
            raise parsedData["bozo_exception"]
    except Exception:
        traceID = ExceptionProcess.catch()
        raise BotProgramError(reason="处理RSS订阅数据失败", trace=traceID)

    logger.debug(f"The RSS feed information is as follows: {str(parsedData)[:100]}...")

    feedInfo: dict = parsedData.feed
    returnInfo = {
        "title": feedInfo["title"],
        "subtitle": feedInfo.get("subtitle"),
        "link": feedInfo.get("link"),
        "last_update": feedInfo.get("updated"),
        "last_update_stamp": _parseTime(feedInfo.get("updated_parsed")),
        "published": feedInfo.get("published"),
        "published_stamp": _parseTime(feedInfo.get("published_parsed")),
        "version": parsedData.get("version"),
        "token": _generateToken(feedInfo["link"]),
    }

    feedContent: dict
    feedContents = [
        {
            "title": feedContent["title"],
            "link": feedContent["link"],
            "id": feedContent.get("id"),
            "published": feedContent.get("published"),
            "published_stamp": _parseTime(feedContent.get("published_parsed")),
            "author": feedContent.get("author"),
            "all_author": "/".join(i["name"] for i in feedContent.get("authors", [])),
            "summary": feedContent.get("summary"),
        }
        for feedContent in parsedData.entries
    ]

    feedContents.sort(key=lambda x: x["published_stamp"], reverse=True)

    returnInfo.update({"content": feedContents, "size": len(feedContents)})
    return returnInfo
Пример #6
0
    async def wrapper(session: UnionSession, *args, **kwargs):
        assert isinstance(session, BaseSession)
        sessionType = type(session)

        sessionMessage: str = extract_text(session.ctx["message"])

        enabled = (
            PluginManager.settings(pluginName=pluginName, ctx=session.ctx).status
            if pluginName
            else True
        )

        logger.debug(
            "Session information:"
            + ",".join(
                [
                    f"type={sessionType.__name__}",
                    f"plugin={pluginName}",
                    f"content={sessionMessage.__repr__()}",
                    f"ctx={session.ctx}",
                    f"enabled={enabled}",
                ]
            )
        )

        if isinstance(session, CommandSession):
            cancelController = handle_cancellation(session)
            cancelController(sessionMessage)

        try:
            if not enabled:
                if isinstance(session, CommandSession):
                    raise BotDisabledError
                else:
                    return
            execSession = SyncWrapper(session) if convertToSync else session
            return await function(execSession, *args, **kwargs)

        except (_FinishException, _PauseException, SwitchException, ValidateError):
            raise
        except BotDisabledError as e:
            if not e.trace:
                e.trace = ExceptionProcess.catch()
            return f"已经被禁用,原因:{e.reason},追踪ID:{e.trace}"
        except BotRequestError as e:
            if not e.trace:
                e.trace = ExceptionProcess.catch()
            return f"请求资源失败,原因:{e.reason},追踪ID:{e.trace}"
        except BotMessageError as e:
            if not e.trace:
                e.trace = ExceptionProcess.catch()
            return f"信息发送失败,原因:{e.reason},追踪ID:{e.trace}"
        except BotNotFoundError as e:
            if not e.trace:
                e.trace = ExceptionProcess.catch()
            return f"未找到,原因:{e.reason},追踪ID:{e.trace}"
        except BotExistError as e:
            if not e.trace:
                e.trace = ExceptionProcess.catch()
            return f"已存在,原因:{e.reason},追踪ID:{e.trace}"
        except BotPermissionError as e:
            if not e.trace:
                e.trace = ExceptionProcess.catch()
            return f"您不具有权限,原因:{e.reason},追踪ID:{e.trace}"
        except BotNetworkError as e:
            if not e.trace:
                e.trace = ExceptionProcess.catch()
            return f"网络出错,原因:{e.reason},追踪ID:{e.trace}"
        except BotProgramError as e:
            if not e.trace:
                e.trace = ExceptionProcess.catch()
            return f"程序出错,原因:{e.reason},追踪ID:{e.trace}"
        except BaseBotError as e:
            if not e.trace:
                e.trace = ExceptionProcess.catch()
            return f"基础组件出错,原因:{e.reason},追踪ID:{e.trace}"
        except AssertionError as e:
            return f"程序抛出断言,原因:{e},追踪ID:{ExceptionProcess.catch()}"
        except Exception:
            from loguru import logger as loguruLogger

            traceID = ExceptionProcess.catch()
            loguruLogger.exception(
                f"An unknown error (ID:{traceID}) occurred while"
                + f'processing message {session.ctx["message_id"]}:'
            )

            if not sessionType == CommandSession:
                return
            return f"出现未知错误,追踪ID:{traceID},请联系开发者"