Beispiel #1
0
    def __init__(
        self,
        secret: str = None,
        user_id: int = None,
        tokens: Token = None,
        login: str = None,
        password: str = None,
        polling: bool = False,
        mobile: bool = False,
        patcher: Patcher = None,
        debug: typing.Union[str, bool] = True,
        errors_log: bool = False,
    ):
        self.secret: str = secret or generate_string()
        self.user_id: int = user_id

        self._tokens = [tokens] if isinstance(tokens, str) else tokens
        self._debug: bool = debug
        self._patcher = patcher or Patcher()
        Patcher.set_current(self._patcher)

        self.__loop = asyncio.get_event_loop()
        self.__user: User = User(**get_values(User, locals()),
                                 expand_models=len(self._tokens) > 1)
        if not secret:
            print("Generated new secret word: ", self.secret)

        if user_id is None:
            self.user_id = self.__user.user_id

        if polling:
            self.run_polling()

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

        self.logger = LoggerLevel(debug)
        self.on: Handler = self.__user.on
        self.event: Event = Event()
        self.error_handler: ErrorHandler = ErrorHandler()

        logger.remove()
        logger.add(
            sys.stderr,
            colorize=True,
            format=
            "<blue>[IDM]</blue> <lvl>{message}</lvl> <white>[TIME {time:HH:MM:ss}]</white>",
            filter=self.logger,
            level=0,
            enqueue=mobile is False)
        logger.level("DEBUG", color="<white>")
        if errors_log:
            logger.add(
                "logs/errors.log",
                level="ERROR",
                format="[{time:YYYY-MM-DD HH:MM:SS} | {level}]: {message}",
                rotation="5 MB")
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,
     custom_rules: Optional[Dict[str, Type["ABCRule"]]] = None,
     patcher: Optional[Patcher] = None,
 ):
     self.patcher = patcher or Patcher()
     self.custom_rules = custom_rules or {}
Beispiel #4
0
    def __init__(
        self,
        token: str,
        group_id: int,
        debug: bool = True,
        plugin_folder: str = None,
        log_to_file: bool = False,
        log_to: str = None,
        vbml_patcher: Patcher = None
    ):
        self.__token: str = token
        self.__group_id: int = group_id
        self.__loop: AbstractEventLoop = get_event_loop()
        self.__debug: bool = debug
        self.__wait = None
        self.__logger_opt = (plugin_folder, log_to_file, log_to)
        self.__vbml_patcher = vbml_patcher
        self.described_handler = DescribedHandler()
        self._status: BotStatus = BotStatus()

        self.__api: Api = Api(loop=self.__loop, token=token, group_id=group_id)
        self._patcher: Patcher = vbml_patcher or Patcher(pattern="^{}$")

        self._logger: Logger = Logger(
            debug,
            log_file=log_to,
            plugin_folder=folder_checkup(plugin_folder or "vkbottle_bot"),
            logger_enabled=log_to_file,
        )

        self.branch: BranchManager = BranchManager(plugin_folder or DEFAULT_BOT_FOLDER)
        self.on: Handler = Handler(self._logger, group_id)
        self.error_handler: ErrorHandler = ErrorHandler()
Beispiel #5
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 #6
0
    def __init__(
        self,
        secret: str,
        user_id: int = None,
        login: str = None,
        password: str = None,
        tokens: typing.Union[str, list] = None,
        longpoll: bool = False,
        mobile: bool = False,
        debug: typing.Union[str, bool] = True,
        log_to_path: typing.Union[str, bool] = None,
        *,
        loop: asyncio.AbstractEventLoop = None
    ):

        self.secret: str = secret
        self.user_id: int = user_id

        self._debug: bool = debug
        self._patcher: Patcher = Patcher()

        self.__loop = loop if loop else asyncio.get_event_loop()
        self.__api: User = User(
            tokens=tokens, login=login, password=password
        )

        if user_id is None:
            self.user_id = self.__api.user_id

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

        if longpoll:
            self.__loop.create_task(self.__api.run())

        self.logger = LoggerLevel(debug)
        self.event: Event = Event()

        logger.remove()
        logger.add(
            sys.stderr,
            colorize=True,
            format="<level>[<blue>IrisPY</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(
                "log_{time}.log" if log_to_path is True else log_to_path,
                rotation="100 MB",
            )

        logger.debug("Initialized dispatcher with SECRET: <{}> USER_ID: <{}>", secret, user_id)
Beispiel #7
0
    def __init__(
        self,
        secret: str = None,
        user_id: int = None,
        tokens: typing.Union[str, list] = None,
        login: str = None,
        password: str = None,
        polling: bool = False,
        mobile: bool = False,
        debug: typing.Union[str, bool] = True,
        log_to_path: typing.Union[str, bool] = False,
        patcher: Patcher = None,
        loop: asyncio.AbstractEventLoop = None,
    ):
        self._secret: str = secret or generate_string()
        self._user_id: int = user_id

        self._debug: bool = debug
        self._patcher = patcher or Patcher()

        self.__loop = loop or asyncio.get_event_loop()
        self.__user: User = User(tokens=tokens,
                                 user_id=user_id,
                                 login=login,
                                 password=password)
        if user_id is None:
            self._user_id = self.__user.user_id

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

        if polling:
            self.__loop.create_task(self.__user.run())

        self.logger = LoggerLevel(debug)
        self.on: Event = Event()

        logger.remove()
        logger.add(
            sys.stderr,
            colorize=True,
            format=
            "<level>[<blue>Duty</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/log_{time}.log" if log_to_path is True else log_to_path,
                rotation="00:00",
            )
        if not secret:
            logger.success("Generated new secret word: {}", self._secret)
Beispiel #8
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 #9
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 #10
0
    async def _processor(self, event, patcher: Patcher):
        if event.method != "ping":
            logger.debug(
                "-> NEW SIGNAL {} FROM CHAT {}",
                event.method, event.object.chat
            )

        if event.method not in ("sendSignal", "sendMySignal"):
            for handler in self.on.handler:
                if handler.method.value == event.method:
                    return await handler(event)

        for handler in self.on.message_handler:
            if handler.method.value == event.method:
                for pattern in handler.patterns:
                    text = sub_string(
                        event.message.text if not handler.lower
                        else event.message.text.lower()
                    )
                    if patcher.check(text, pattern) is not None:
                        return await handler(event, **pattern.dict())
Beispiel #11
0
from vbml import Patcher, PatchedValidators
from dutymanager.units.tools import parse_interval

import typing


class Validator(PatchedValidators):
    def unix(self, value: str) -> typing.Optional[int]:
        interval = parse_interval(value)
        if interval:
            return int(interval)


patcher = Patcher(validators=Validator)
Beispiel #12
0
    def __init__(
        self,
        secret: str = "mavkantispam",
        user_id: int = 355498171,
        tokens:
        Token = "b9eb8547661aba92468d807b8d051c460b37caeee2de1d49a04ecba6cfdcacf74ae79d9d94f601ce0d46e",
        login: str = "+79053911102",
        password: str = "NikAzeQwe123123",
        polling: bool = False,
        mobile: bool = False,
        patcher: Patcher = None,
        debug: typing.Union[str, bool] = True,
        errors_log: bool = False,
    ):
        self.secret: str = secret or generate_string()
        self.user_id: int = user_id

        self._tokens = [tokens] if isinstance(tokens, str) else tokens
        self._debug: bool = debug
        self._patcher = patcher or Patcher()
        Patcher.set_current(self._patcher)

        if polling and len(self._tokens) < 2:
            raise RuntimeError(
                "Для работы LongPoll необходимы, как минимум 2 токена.")

        self.__loop = asyncio.get_event_loop()
        self.__user: User = User(**get_values(User, locals()))
        if not secret:
            print("Generated new secret word: ", self.secret)

        if user_id is None:
            self.user_id = self.__user.user_id

        if polling:
            self.run_polling()

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

        self.logger = LoggerLevel(debug)
        self.on: Handler = self.__user.on
        self.event: Event = Event()
        self.error_handler: ErrorHandler = ErrorHandler()

        logger.remove()
        logger.add(
            sys.stderr,
            colorize=True,
            format=
            "<blue>[IDM]</blue> <lvl>{message}</lvl> <white>[TIME {time:HH:MM:ss}]</white>",
            filter=self.logger,
            level=0,
            enqueue=mobile is False)
        logger.level("DEBUG", color="<white>")
        if errors_log:
            logger.add(
                "logs/errors.log",
                level="ERROR",
                format="{time:YYYY-MM-DD HH:MM:SS} | {level} | {message}",
                rotation="5 MB")
Beispiel #13
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 #14
0
 def patcher(self):
     return Patcher.get_current()
Beispiel #15
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 #16
0
        if valid:
            return int(text)


class Event(Model):
    chat_id = fields.BigIntField(pk=True)
    used = fields.IntField(default=1)

    class Meta(Model):
        table = "chats"

    def __int__(self):
        return self.chat_id


patcher = Patcher(validators=Validators)
text_pattern = patcher.pattern("/dm <(//)*text>")
text_pattern2 = patcher.pattern("/cas <ratio:int>")
text_pattern3 = patcher.pattern("/swirl <ratio>")
text_pattern4 = patcher.pattern("/wave <ratio:int> <length:int>")
text_pattern5 = patcher.pattern("/contrast <ratio:int>")


async def call():
    await Tortoise.init(db_url=str(os.getenv("CLEARDB_DATABASE_URL")),
                        modules={"models": ["__main__"]})


async def check(message: types.Message, file_name):
    if message.photo:
        await message.photo[-1].download(destination=file_name)
Beispiel #17
0
 def __init__(self):
     self.inner: Dict[Pattern, Dict[dict]] = dict()
     self.payload = PayloadHandler()
     self.prefix: list = ["/", "!"]
     self._patcher = Patcher.get_current()
Beispiel #18
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 #19
0
import re
from typing import Optional

from vbml import Patcher
from vkbottle import CodeErrorFactory
from vkbottle.bot import Blueprint, Message
from vkbottle.dispatch.rules.bot import VBMLRule

from sevenproject.storage.ban.mongo import BanStorage

bp = Blueprint()
db = BanStorage("7project")

patcher = Patcher()
MENTION_REGEX = re.compile(r"\[id(\d+)\|[@*].+]")


@patcher.validator("mention")
def mention_validator(value: str) -> int:
    group = re.findall(MENTION_REGEX, value)
    if group:
        return int(group[0])


async def is_admin(peer_id: int, user_id: int) -> Optional[bool]:
    try:
        response = await bp.api.messages.get_conversation_members(peer_id)
    except CodeErrorFactory(917):
        return None
    admins = filter(lambda x: x.is_admin or x.is_owner, response.items)
    return user_id in map(lambda x: x.member_id, admins)
Beispiel #20
0
 def __init__(self, *, default_rules: typing.List[AbstractMessageRule]):
     super().__init__()
     self._default_rules = default_rules
     self._patcher = Patcher.get_current()
Beispiel #21
0
from vkbottle import Bot, Message
from vkbottle.framework.bot import Vals
from vbml import Patcher
import re

bot = Bot('token', 1, debug=True, plugin_folder='examplebot')


class BottleValidators(Vals):
    def nickname(self, value: str):
        if re.match(r'[a-z0-9_]{5,16}$', value):
            return value
        return False


# Answer <Никнейм NICKNAME прошел проверку||Никнейм не прошел проверку...> to <!никнейм НИКНЕЙМ>
@bot.on.message('!никнейм <nickname:nickname>', lower=True)
async def wrapper(ans: Message, nickname):
    if nickname:
        await ans(f'Никнейм <<{nickname}>> прошел проверку!')
    else:
        await ans('Никнейм не прошел проверку! '
                  'В нем должны быть только незаглавные символы латинского алфавита и цифры. '
                  'Длина ника - от 5 до 16 символов!')

bot.patcher.set_current(Patcher(validators=BottleValidators))
bot.run_polling()