Beispiel #1
0
    def __init__(
        self,
        pattern: typing.Union[
            str,
            Pattern,
            typing.List[typing.Union[str, Pattern]],
            typing.Dict[typing.Union[str, Pattern], typing.Union[list, dict]],
        ],
        lower: bool = None,
    ):
        if isinstance(pattern, dict):
            self.watch_context = pattern
            pattern = list(pattern.keys())
            print(pattern)
        self._patcher = Patcher.get_current()
        patterns: typing.List[Pattern] = []
        if isinstance(pattern, Pattern):
            patterns = [pattern]
        elif isinstance(pattern, list):
            for p in pattern:
                if isinstance(p, str):
                    patterns.append(
                        self._patcher.pattern(p, flags=re.IGNORECASE if lower else None)
                    )
                else:
                    patterns.append(p)
        elif isinstance(pattern, str):
            patterns = [self._patcher.pattern(pattern)]

        self.data = {"pattern": patterns}
Beispiel #2
0
    def __init__(self, group_id: int = 0, patcher: Patcher = Patcher()):
        self.group_id: int = group_id
        self.message_rules: typing.List[typing.List[AbstractRule]] = list()

        self.message: MessageHandler = MessageHandler(
            default_rules=[PrivateMessage()])
        self.chat_message: MessageHandler = MessageHandler(
            default_rules=[ChatMessage()])
        self.message_handler: MessageHandler = MessageHandler(
            default_rules=[Any()])
        self.event: BotEvents = BotEvents()

        self._pre_p: typing.Optional[typing.Callable] = None
        self._patcher = Patcher.get_current() or patcher
Beispiel #3
0
    def __init__(self, group_id: int = 0, patcher: Patcher = Patcher()):
        self.group_id: int = group_id
        self.rules: typing.List[typing.List[AbstractRule]] = list()

        self.message: MessageHandler = MessageHandler(default_rules=[PrivateMessage()])
        self.chat_message: MessageHandler = MessageHandler(
            default_rules=[ChatMessage()]
        )
        self.message_handler: MessageHandler = MessageHandler(default_rules=[Any()])
        self.event: Event = Event()

        self._pre_p: typing.Optional[typing.Callable] = None
        self._patcher = Patcher.get_current() or patcher

        if not hasattr(Pattern, "context_copy"):
            raise RuntimeError(
                "\n\n\tNow! Update vbml with command:\n"
                "\tpip install https://github.com/timoniq/vbml/archive/master.zip --upgrade\n"
                "\ttnx <3"
            )
Beispiel #4
0
    def __init__(self, logger: Logger, group_id: int = 0):
        self.__group_id: int = group_id
        self.__logger = logger

        self.message: MessageHandler = MessageHandler()
        self.chat_message: MessageHandler = MessageHandler()
        self.message_both: MessageHandler = MessageHandler()
        self.event: Event = Event()
        self._pre_p: Optional[Callable] = None

        self.__undefined_message_func = None
        self.__chat_action_types: list = list()

        self._patcher = Patcher.get_current()

        if not hasattr(Pattern, "context_copy"):
            raise RuntimeError(
                "\n\n\tNow! Update vbml with command:\n"
                "\tpip install https://github.com/timoniq/vbml/archive/master.zip --upgrade\n"
                "\ttnx <3")
Beispiel #5
0
 def patcher(self):
     return Patcher.get_current()
Beispiel #6
0
 def __init__(self, default_rules: typing.List = None):
     self.rules: typing.List[typing.List[UserLongPollEventRule]] = list()
     self._default_rules = default_rules or []
     self._patcher = Patcher.get_current()
     self.prefix: list = ["/", "!"]
Beispiel #7
0
    def __init__(
        self,
        tokens: Token = None,
        *,
        group_id: int = None,
        debug: typing.Union[str, bool] = True,
        loop: asyncio.AbstractEventLoop = None,
        throw_errors: bool = True,
        log_to_path: typing.Union[str, bool] = None,
        patcher: Patcher = None,
        mobile: bool = False,
        secret: str = None,
        extension: AbstractExtension = None,
        logs_folder: typing.Optional[str] = None,
        only_asyncio_loop: bool = False,
        **context,
    ):
        """
        Init bot
        :param tokens: bot tokens
        :param group_id:
        :param debug: should bot debug messages for emulating
        :param log_to_path: make logs
        :param secret: secret vk code for callback
        :param extension:
        """
        # Base bot classifiers
        self.__tokens: typing.List[str] = [tokens] if isinstance(
            tokens, str
        ) else tokens
        self.__debug: bool = debug
        self.__wait = None
        self.__secret = secret
        self._status: BotStatus = BotStatus()

        self.context: dict = context

        if uvloop is not None:
            if not only_asyncio_loop:
                asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())

        if isinstance(debug, bool):
            debug = "INFO" if debug else "ERROR"

        self.logger = LoggerLevel(debug)

        if not Patcher.get_current():
            Patcher.set_current(
                patcher
                if patcher is not None
                else Patcher(pattern="^{}$", validators=DefaultValidators)
            )

        logger.remove()
        logger.add(
            sys.stderr,
            colorize=True,
            format="<level>[<blue>VKBottle</blue>] {message}</level> <white>[TIME {time:HH:MM:ss}]</white>",
            filter=self.logger,
            level=0,
            enqueue=mobile is False,
        )
        logger.level("INFO", color="<white>")
        logger.level("ERROR", color="<red>")
        if log_to_path:
            logger.add(
                (logs_folder or "") + "log_{time}.log"
                if log_to_path is True
                else log_to_path,
                rotation="20 MB",
            )

        self.group_id = group_id or self.get_id_by_token(self.__tokens[0])
        self.__loop = loop or asyncio.get_event_loop()

        # Sign assets
        self.api: Api = Api(self.__tokens, throw_errors=throw_errors)
        self.extension: AbstractExtension = extension if extension is not None else StandardExtension()

        self._throw_errors: bool = throw_errors
        Api.set_current(self.api)
        AbstractExtension.set_current(self.extension)

        # Main workers
        self.branch: typing.Union[AbstractBranchGenerator, DictBranch] = DictBranch()
        self.middleware: MiddlewareExecutor = MiddlewareExecutor()
        self.on: Handler = Handler(self.group_id)
        self.error_handler: VKErrorHandler = DefaultErrorHandler()

        self._stop: bool = False

        logger.info("Using JSON_MODULE - {}".format(USAGE))
        logger.info(
            "Using asyncio loop - {}".format(
                asyncio.get_event_loop_policy().__class__.__module__
            )
        )
Beispiel #8
0
 def __init__(self, default_rules: typing.List = None):
     self.payload: PayloadHandler = PayloadHandler()
     self.rules: typing.List[typing.List[AbstractRule]] = list()
     self._default_rules = default_rules or []
     self.prefix: list = ["/", "!"]
     self._patcher = Patcher.get_current()
Beispiel #9
0
 def __init__(self, *, default_rules: typing.List[AbstractMessageRule]):
     super().__init__()
     self._default_rules = default_rules
     self._patcher = Patcher.get_current()
Beispiel #10
0
 def __init__(self):
     self.inner: Dict[Pattern, Dict[dict]] = dict()
     self.payload = PayloadHandler()
     self.prefix: list = ["/", "!"]
     self._patcher = Patcher.get_current()