Пример #1
0
        def wrapper(func: callable) -> callable:
            events.register(NewMessage(**kwargs))(func)

            if edited:
                events.register(MessageEdited(**kwargs))(func)

            if self.register_commands and command:
                handlers = events._get_handlers(func)
                category = "misc"
                if isinstance(command, tuple):
                    if len(command) == 2:
                        com, category = command
                    else:
                        raise ValueError
                else:
                    com = command

                UBcommand = Command(
                    func, handlers, info or inspect.cleandoc(func.__doc__)
                    or no_info, builtin)
                category = category.lower()
                self.commands.update({com: UBcommand})
                update_dict(self.commandcategories, category, com)
                if builtin:
                    update_dict(self.commandcategories, 'builtin', com)
            return func
Пример #2
0
        def wrapper(func: callable) -> callable:
            events.register(NewMessage(**kwargs))(func)

            if edited:
                events.register(MessageEdited(**kwargs))(func)

            if self.register_commands and command:
                handlers = events._get_handlers(func)
                category = "misc"
                doc_kwargs.setdefault('prefix', self.prefix or '.')
                if isinstance(command, tuple):
                    if len(command) == 2:
                        com, category = command
                    else:
                        raise ValueError
                else:
                    com = command
                help_doc = info or func.__doc__ or no_info

                UBcommand = Command(
                    func, handlers,
                    inspect.cleandoc(help_doc).format(**doc_kwargs), builtin)
                category = category.lower()
                self.commands.update({com: UBcommand})
                self.commandcategories.setdefault(category, []).append(com)
                if builtin:
                    self.commandcategories.setdefault('builtin',
                                                      []).append(com)
            return func
Пример #3
0
        def wrapper(func):
            events.register(NewMessage(**kwargs))(func)

            if edited:
                events.register(MessageEdited(**kwargs))(func)

            if self.register_commands and command:
                handlers = events._get_handlers(func)
                self.commands.update(
                    {command: Command(func, handlers, info, builtin)})

            return func
Пример #4
0
    def add_event_handler(self: 'TelegramClient',
                          callback: callable,
                          event: EventBuilder = None):
        """
        Registers a new event handler callback.

        The callback will be called when the specified event occurs.

        Arguments
            callback (`callable`):
                The callable function accepting one parameter to be used.

                Note that if you have used `telethon.events.register` in
                the callback, ``event`` will be ignored, and instead the
                events you previously registered will be used.

            event (`_EventBuilder` | `type`, optional):
                The event builder class or instance to be used,
                for instance ``events.NewMessage``.

                If left unspecified, `telethon.events.raw.Raw` (the
                :tl:`Update` objects with no further processing) will
                be passed instead.

        Example
            .. code-block:: python

                from telethon import TelegramClient, events
                client = TelegramClient(...)

                async def handler(event):
                    ...

                client.add_event_handler(handler, events.NewMessage)
        """
        builders = events._get_handlers(callback)
        if builders is not None:
            for event in builders:
                self._event_builders.append((event, callback))
            return

        if isinstance(event, type):
            event = event()
        elif not event:
            event = events.Raw()

        self._event_builders.append((event, callback))
Пример #5
0
    def _import_plugin(self, name: str, path: str, content: str) -> None:
        """Import file and bytecode plugins."""
        to_overwrite: Union[None, str] = None
        callbacks: List[Callback] = []
        ppath = self.plugin_path.absolute() / name.replace(".", "/") / ".py"
        ubotpath = "userbot.plugins." + name
        log = "Successfully imported {}".format(name)

        for plugin in self.active_plugins:
            if plugin.name == name:
                LOGGER.info("Overwritting %s with %s.", plugin.path, path)
                to_overwrite = plugin
        if to_overwrite:
            self.active_plugins.remove(to_overwrite)

        try:
            if content:
                spec = importlib.machinery.ModuleSpec(path,
                                                      SourcelessPluginLoader(
                                                          ubotpath, content,
                                                          path),
                                                      origin=path)
                match = github_raw_pattern.search(path)
                log += " from {}".format(match.group(1))
            else:
                # Local files use SourceFileLoader
                spec = importlib.util.find_spec(path)

            module = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(module)
            # To make plugins impoartable use "sys.modules[path] = module".
            sys.modules[ubotpath] = module

            for n, cb in vars(module).items():
                if inspect.iscoroutinefunction(cb) and not n.startswith("_"):
                    if events._get_handlers(cb):
                        callbacks.append(Callback(n, cb))

            self.active_plugins.append(Plugin(name, callbacks, ppath, module))
            LOGGER.info(log)
        except Exception as e:
            self.client.failed_imports.append(path)
            LOGGER.error("Failed to import %s due to the error(s) below.",
                         path)
            LOGGER.exception(e)
Пример #6
0
        def wrapper(func: callable) -> callable:
            events.register(NewMessage(**kwargs))(func)

            if edited:
                events.register(MessageEdited(**kwargs))(func)

            if self.register_commands and command:
                handlers = events._get_handlers(func)
                category = "misc"
                doc_args.setdefault("prefix", self.prefix or ".")
                if isinstance(command, tuple):
                    if len(command) == 2:
                        com, category = command
                    else:
                        raise ValueError
                else:
                    com = command
                help_doc = info or func.__doc__ or no_info
                _doc = inspect.cleandoc(help_doc).split("\n\n\n", maxsplit=1)
                if len(_doc) > 1:
                    comInfo = _doc[0].strip()
                    comUsage = _doc[1].strip()
                else:
                    comInfo = _doc[0]
                    comUsage = no_usage

                UBcommand = Command(
                    func,
                    handlers,
                    comInfo.format(**doc_args).strip(),
                    comUsage.strip(),
                    builtin,
                )
                category = category.lower()
                self.commands.update({com: UBcommand})
                self.commandcategories.setdefault(category, []).append(com)
                if builtin:
                    self.commandcategories.setdefault("builtin",
                                                      []).append(com)
            return func
Пример #7
0
    def add_event_handler(
        self,
        callback: Union[Callable, Callback],
        event=None,
        *filters: Union[Callable, Filter],
    ):
        if filters is not None and not isinstance(filters, Sequence):
            filters = (filters, )

        _has_state_checker = False
        for filter_ in filters:
            if not isinstance(filter_, (Filter, Callable)):
                raise ValueError(
                    f"Got {type(filter_).__qualname__}, expected Filter or Callable"
                )

            if isinstance(filter_, Filter) and filter_.state_op:
                _has_state_checker = True

        if _has_state_checker is False:
            filters = list(filters)
            filters.append(~state.every())
            filters = tuple(filters)

        if not isinstance(callback, Callback):
            callback = Callback(callback, *filters)

        builders = _get_handlers(callback.__call__)
        if builders is not None:
            for event in builders:
                self._event_builders.append((event, callback))
            return

        if isinstance(event, type):
            event = event()
        elif not event:
            event = Raw()

        self._event_builders.append((event, callback))
Пример #8
0
 def _import_module(self, name: str, path: str):
     for plugin in self.active_plugins:
         if plugin.name == name:
             LOGGER.error("Rename the plugin %s in %s or %s and try again.",
                          name, path, plugin.path)
             exit(1)
     try:
         spec = util.find_spec(path)
         module = util.module_from_spec(spec)
         spec.loader.exec_module(module)
         # To make plugins impoartable use "sys.modules[path] = module".
         callbacks: List[Callback] = []
         for n, cb in vars(module).items():
             if iscoroutinefunction(cb) and not n.startswith('_'):
                 if _get_handlers(cb):
                     callbacks.append(Callback(n, cb))
         self.active_plugins.append(Plugin(name, callbacks, path, module))
         LOGGER.info("Successfully Imported %s", name)
     except Exception as E:
         LOGGER.error("Failed to import %s due to the error(s) below.",
                      path)
         LOGGER.exception(E)