RepoPeft-data / oracle_context_cache /DonDebonair__slack-machine.json
nanigock's picture
Upload folder using huggingface_hub
cd15502 verified
{"repo": "DonDebonair/slack-machine", "n_pairs": 109, "version": "v2_function_scoped", "contexts": {"tests/test_import_settings.py::8": {"resolved_imports": ["src/machine/settings.py"], "used_names": ["import_settings"], "enclosing_function": "test_normal_import_settings", "extracted_code": "# Source: src/machine/settings.py\ndef import_settings(settings_module: str = \"local_settings\") -> tuple[CaseInsensitiveDict, bool]:\n default_settings = {\n \"PLUGINS\": [\n \"machine.plugins.builtin.general.PingPongPlugin\",\n \"machine.plugins.builtin.general.HelloPlugin\",\n \"machine.plugins.builtin.help.HelpPlugin\",\n \"machine.plugins.builtin.fun.memes.MemePlugin\",\n ],\n \"STORAGE_BACKEND\": \"machine.storage.backends.memory.MemoryStorage\",\n \"HTTP_PROXY\": None,\n \"TZ\": \"UTC\",\n \"LOG_HANDLED_MESSAGES\": True,\n }\n settings = CaseInsensitiveDict(default_settings)\n try:\n local_settings = import_module(settings_module)\n found_local_settings = True\n except ImportError:\n found_local_settings = False\n else:\n for k in dir(local_settings):\n if not k.startswith(\"_\"):\n settings[k] = getattr(local_settings, k)\n\n for k, v in os.environ.items():\n if k[:3] == \"SM_\":\n k = k[3:]\n settings[k] = v\n\n return settings, found_local_settings", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1108}, "tests/test_import_settings.py::19": {"resolved_imports": ["src/machine/settings.py"], "used_names": ["import_settings"], "enclosing_function": "test_normal_import_settings", "extracted_code": "# Source: src/machine/settings.py\ndef import_settings(settings_module: str = \"local_settings\") -> tuple[CaseInsensitiveDict, bool]:\n default_settings = {\n \"PLUGINS\": [\n \"machine.plugins.builtin.general.PingPongPlugin\",\n \"machine.plugins.builtin.general.HelloPlugin\",\n \"machine.plugins.builtin.help.HelpPlugin\",\n \"machine.plugins.builtin.fun.memes.MemePlugin\",\n ],\n \"STORAGE_BACKEND\": \"machine.storage.backends.memory.MemoryStorage\",\n \"HTTP_PROXY\": None,\n \"TZ\": \"UTC\",\n \"LOG_HANDLED_MESSAGES\": True,\n }\n settings = CaseInsensitiveDict(default_settings)\n try:\n local_settings = import_module(settings_module)\n found_local_settings = True\n except ImportError:\n found_local_settings = False\n else:\n for k in dir(local_settings):\n if not k.startswith(\"_\"):\n settings[k] = getattr(local_settings, k)\n\n for k, v in os.environ.items():\n if k[:3] == \"SM_\":\n k = k[3:]\n settings[k] = v\n\n return settings, found_local_settings", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1108}, "tests/test_import_settings.py::27": {"resolved_imports": ["src/machine/settings.py"], "used_names": ["import_settings"], "enclosing_function": "test_import_settings_non_existing_module", "extracted_code": "# Source: src/machine/settings.py\ndef import_settings(settings_module: str = \"local_settings\") -> tuple[CaseInsensitiveDict, bool]:\n default_settings = {\n \"PLUGINS\": [\n \"machine.plugins.builtin.general.PingPongPlugin\",\n \"machine.plugins.builtin.general.HelloPlugin\",\n \"machine.plugins.builtin.help.HelpPlugin\",\n \"machine.plugins.builtin.fun.memes.MemePlugin\",\n ],\n \"STORAGE_BACKEND\": \"machine.storage.backends.memory.MemoryStorage\",\n \"HTTP_PROXY\": None,\n \"TZ\": \"UTC\",\n \"LOG_HANDLED_MESSAGES\": True,\n }\n settings = CaseInsensitiveDict(default_settings)\n try:\n local_settings = import_module(settings_module)\n found_local_settings = True\n except ImportError:\n found_local_settings = False\n else:\n for k in dir(local_settings):\n if not k.startswith(\"_\"):\n settings[k] = getattr(local_settings, k)\n\n for k, v in os.environ.items():\n if k[:3] == \"SM_\":\n k = k[3:]\n settings[k] = v\n\n return settings, found_local_settings", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1108}, "tests/test_import_settings.py::9": {"resolved_imports": ["src/machine/settings.py"], "used_names": ["import_settings"], "enclosing_function": "test_normal_import_settings", "extracted_code": "# Source: src/machine/settings.py\ndef import_settings(settings_module: str = \"local_settings\") -> tuple[CaseInsensitiveDict, bool]:\n default_settings = {\n \"PLUGINS\": [\n \"machine.plugins.builtin.general.PingPongPlugin\",\n \"machine.plugins.builtin.general.HelloPlugin\",\n \"machine.plugins.builtin.help.HelpPlugin\",\n \"machine.plugins.builtin.fun.memes.MemePlugin\",\n ],\n \"STORAGE_BACKEND\": \"machine.storage.backends.memory.MemoryStorage\",\n \"HTTP_PROXY\": None,\n \"TZ\": \"UTC\",\n \"LOG_HANDLED_MESSAGES\": True,\n }\n settings = CaseInsensitiveDict(default_settings)\n try:\n local_settings = import_module(settings_module)\n found_local_settings = True\n except ImportError:\n found_local_settings = False\n else:\n for k in dir(local_settings):\n if not k.startswith(\"_\"):\n settings[k] = getattr(local_settings, k)\n\n for k, v in os.environ.items():\n if k[:3] == \"SM_\":\n k = k[3:]\n settings[k] = v\n\n return settings, found_local_settings", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1108}, "tests/test_import_settings.py::50": {"resolved_imports": ["src/machine/settings.py"], "used_names": ["import_settings", "patch"], "enclosing_function": "test_env_import_settings", "extracted_code": "# Source: src/machine/settings.py\ndef import_settings(settings_module: str = \"local_settings\") -> tuple[CaseInsensitiveDict, bool]:\n default_settings = {\n \"PLUGINS\": [\n \"machine.plugins.builtin.general.PingPongPlugin\",\n \"machine.plugins.builtin.general.HelloPlugin\",\n \"machine.plugins.builtin.help.HelpPlugin\",\n \"machine.plugins.builtin.fun.memes.MemePlugin\",\n ],\n \"STORAGE_BACKEND\": \"machine.storage.backends.memory.MemoryStorage\",\n \"HTTP_PROXY\": None,\n \"TZ\": \"UTC\",\n \"LOG_HANDLED_MESSAGES\": True,\n }\n settings = CaseInsensitiveDict(default_settings)\n try:\n local_settings = import_module(settings_module)\n found_local_settings = True\n except ImportError:\n found_local_settings = False\n else:\n for k in dir(local_settings):\n if not k.startswith(\"_\"):\n settings[k] = getattr(local_settings, k)\n\n for k, v in os.environ.items():\n if k[:3] == \"SM_\":\n k = k[3:]\n settings[k] = v\n\n return settings, found_local_settings", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1108}, "tests/test_import_settings.py::29": {"resolved_imports": ["src/machine/settings.py"], "used_names": ["import_settings"], "enclosing_function": "test_import_settings_non_existing_module", "extracted_code": "# Source: src/machine/settings.py\ndef import_settings(settings_module: str = \"local_settings\") -> tuple[CaseInsensitiveDict, bool]:\n default_settings = {\n \"PLUGINS\": [\n \"machine.plugins.builtin.general.PingPongPlugin\",\n \"machine.plugins.builtin.general.HelloPlugin\",\n \"machine.plugins.builtin.help.HelpPlugin\",\n \"machine.plugins.builtin.fun.memes.MemePlugin\",\n ],\n \"STORAGE_BACKEND\": \"machine.storage.backends.memory.MemoryStorage\",\n \"HTTP_PROXY\": None,\n \"TZ\": \"UTC\",\n \"LOG_HANDLED_MESSAGES\": True,\n }\n settings = CaseInsensitiveDict(default_settings)\n try:\n local_settings = import_module(settings_module)\n found_local_settings = True\n except ImportError:\n found_local_settings = False\n else:\n for k in dir(local_settings):\n if not k.startswith(\"_\"):\n settings[k] = getattr(local_settings, k)\n\n for k, v in os.environ.items():\n if k[:3] == \"SM_\":\n k = k[3:]\n settings[k] = v\n\n return settings, found_local_settings", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1108}, "tests/test_plugin_registration.py::147": {"resolved_imports": ["src/machine/core.py", "src/machine/clients/slack.py", "src/machine/models/core.py", "src/machine/plugins/decorators.py", "src/machine/utils/collections.py", "src/machine/utils/logging.py"], "used_names": ["Machine", "pytest"], "enclosing_function": "test_plugin_init", "extracted_code": "# Source: src/machine/core.py\nclass Machine:\n _socket_mode_client: SocketModeClient\n _client: SlackClient | None\n _storage_backend: MachineBaseStorage\n _settings: CaseInsensitiveDict | None\n _help: Manual\n _registered_actions: RegisteredActions\n _tz: ZoneInfo\n _scheduler: AsyncIOScheduler\n\n def __init__(self, settings: CaseInsensitiveDict | None = None):\n if settings is not None:\n self._settings = settings\n else:\n self._settings = None\n self._help = Manual(human={}, robot={})\n self._registered_actions = RegisteredActions()\n self._client = None\n\n async def _setup(self) -> None:\n logger.info(\"Initializing Slack Machine...\")\n\n found_local_settings = self._load_settings()\n assert self._settings is not None\n configure_logging(self._settings)\n if not found_local_settings:\n logger.warning(\"No local_settings found! Are you sure this is what you want?\")\n else:\n logger.debug(\"Found local settings %s\", self._settings)\n\n # Check if Slack token are present\n if \"SLACK_APP_TOKEN\" not in self._settings:\n logger.error(\"No SLACK_APP_TOKEN found in settings! I need that to work...\")\n sys.exit(1)\n if \"SLACK_BOT_TOKEN\" not in self._settings:\n logger.error(\"No SLACK_BOT_TOKEN found in settings! I need that to work...\")\n sys.exit(1)\n\n # Setup storage\n await self._setup_storage()\n\n # Setup Slack clients\n await self._setup_slack_clients()\n\n # Setup scheduling\n self._scheduler = AsyncIOScheduler(timezone=self._tz)\n\n # Load plugins\n await self._load_plugins()\n logger.debug(\"Registered plugin actions: %s\", self._registered_actions)\n logger.debug(\"Plugin help: %s\", self._help)\n\n def _load_settings(self) -> bool:\n logger.info(\"Loading settings...\")\n if self._settings is not None:\n found_local_settings = True\n else:\n settings_module = os.environ.get(\"SM_SETTINGS_MODULE\", \"local_settings\")\n self._settings, found_local_settings = import_settings(settings_module=settings_module)\n self._tz = ZoneInfo(self._settings[\"TZ\"])\n logger.info(\"Settings loaded!\")\n return found_local_settings\n\n async def _setup_storage(self) -> None:\n assert self._settings is not None\n storage_backend = self._settings.get(\"STORAGE_BACKEND\", \"machine.storage.backends.memory.MemoryStorage\")\n logger.info(\"Initializing storage backend %s...\", storage_backend)\n _, cls = import_string(storage_backend)[0]\n self._storage_backend = cls(self._settings)\n await self._storage_backend.init()\n logger.info(\"Storage backend %s initialized!\", storage_backend)\n\n async def _setup_slack_clients(self) -> None:\n assert self._settings is not None\n # Setup Slack socket mode client\n self._socket_mode_client = SocketModeClient(\n app_token=self._settings[\"SLACK_APP_TOKEN\"],\n web_client=AsyncWebClient(token=self._settings[\"SLACK_BOT_TOKEN\"]),\n proxy=self._settings[\"HTTP_PROXY\"],\n )\n\n # Setup high-level Slack client for plugins\n self._client = SlackClient(self._socket_mode_client, self._tz)\n await self._client.setup()\n\n # TODO: factor out plugin registration in separate class / set of functions\n async def _load_plugins(self) -> None:\n assert self._settings is not None\n if self._client is None:\n logger.error(\"Slack client not initialized!\")\n sys.exit(1)\n logger.debug(\"PLUGINS: %s\", self._settings[\"PLUGINS\"])\n for plugin in self._settings[\"PLUGINS\"]:\n for class_name, cls in import_string(plugin):\n if issubclass(cls, MachineBasePlugin) and cls is not MachineBasePlugin:\n logger.debug(\"Found a Machine plugin: %s\", plugin)\n storage = PluginStorage(class_name, self._storage_backend)\n instance = cls(self._client, self._settings, storage)\n missing_settings = self._register_plugin(class_name, instance)\n if missing_settings:\n logger.warning(\"Error loading plugin %s\", class_name)\n error_msg = f\"The following settings are missing: {', '.join(missing_settings)}\"\n logger.warning(error_msg)\n del instance\n else:\n await instance.init()\n logger.info(\"Plugin %s loaded\", class_name)\n await self._storage_backend.set(\"manual\", dill.dumps(self._help))\n\n def _register_plugin(self, plugin_class_name: str, cls_instance: MachineBasePlugin) -> list[str] | None:\n missing_settings = []\n cls_instance_for_missing_settings = cast(DecoratedPluginFunc, cls_instance)\n missing_settings.extend(self._check_missing_settings(cls_instance_for_missing_settings))\n methods = inspect.getmembers(cls_instance, predicate=inspect.ismethod)\n for _, fn in methods:\n method_for_missing_settings = cast(DecoratedPluginFunc, fn)\n missing_settings.extend(self._check_missing_settings(method_for_missing_settings))\n if missing_settings:\n return missing_settings\n\n class_help = cls_instance.__doc__.splitlines()[0] if cls_instance.__doc__ else plugin_class_name\n self._help.human[class_help] = self._help.human.get(class_help, {})\n self._help.robot[class_help] = self._help.robot.get(class_help, [])\n for name, fn in methods:\n if hasattr(fn, \"metadata\"):\n self._register_plugin_actions(plugin_class_name, fn.metadata, cls_instance, name, fn, class_help)\n return None\n\n def _check_missing_settings(self, fn_or_class: DecoratedPluginFunc) -> list[str]:\n missing_settings = []\n if hasattr(fn_or_class, \"metadata\") and isinstance(fn_or_class.metadata, Metadata):\n for setting in fn_or_class.metadata.required_settings:\n if self._settings is None or setting not in self._settings:\n missing_settings.append(setting.upper())\n return missing_settings\n\n def _register_plugin_actions(\n self,\n plugin_class_name: str,\n metadata: Metadata,\n cls_instance: MachineBasePlugin,\n fn_name: str,\n fn: Callable[..., Awaitable[None]],\n class_help: str,\n ) -> None:\n fq_fn_name = f\"{plugin_class_name}.{fn_name}\"\n if fn.__doc__:\n self._help.human[class_help][fq_fn_name] = self._parse_human_help(fn.__doc__)\n for matcher_config in metadata.plugin_actions.listen_to:\n self._register_message_handler(\n type_=\"listen_to\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n matcher_config=matcher_config,\n class_help=class_help,\n )\n for matcher_config in metadata.plugin_actions.respond_to:\n self._register_message_handler(\n type_=\"respond_to\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n matcher_config=matcher_config,\n class_help=class_help,\n )\n for event in metadata.plugin_actions.process:\n self._registered_actions.process[event] = self._registered_actions.process.get(event, {})\n key = f\"{fq_fn_name}-{event}\"\n self._registered_actions.process[event][key] = fn\n for command_config in metadata.plugin_actions.commands:\n self._register_command_handler(\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n command_config=command_config,\n class_help=class_help,\n )\n for block_action_config in metadata.plugin_actions.actions:\n self._register_block_action_handler(\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n block_action_config=block_action_config,\n class_help=class_help,\n )\n for modal_config in metadata.plugin_actions.modal_submissions:\n self._register_modal_handler(\n type_=\"modal\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n modal_config=modal_config,\n class_help=class_help,\n )\n for modal_config in metadata.plugin_actions.modal_closures:\n self._register_modal_handler(\n type_=\"modal_closed\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n modal_config=modal_config,\n class_help=class_help,\n )\n\n if metadata.plugin_actions.schedule is not None:\n self._scheduler.add_job(\n fn,\n trigger=\"cron\",\n args=[],\n id=fq_fn_name,\n replace_existing=True,\n **metadata.plugin_actions.schedule,\n )\n\n def _register_message_handler(\n self,\n type_: Literal[\"listen_to\", \"respond_to\"],\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n matcher_config: MatcherConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n handler = MessageHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n regex=matcher_config.regex,\n handle_message_changed=matcher_config.handle_changed_message,\n )\n key = f\"{fq_fn_name}-{matcher_config.regex.pattern}\"\n getattr(self._registered_actions, type_)[key] = handler\n self._help.robot[class_help].append(self._parse_robot_help(matcher_config, type_))\n\n def _register_command_handler(\n self,\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n command_config: CommandConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n logger.debug(\"signature of command handler\", signature=signature, function=fq_fn_name)\n handler = CommandHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n command=command_config.command,\n is_generator=command_config.is_generator,\n )\n command = command_config.command\n if command in self._registered_actions.command:\n logger.warning(\"command was already defined, previous handler will be overwritten!\", command=command)\n self._registered_actions.command[command] = handler\n # TODO: add to help\n\n def _register_block_action_handler(\n self,\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n block_action_config: ActionConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n logger.debug(\"signature of block action handler\", signature=signature, function=fq_fn_name)\n handler = BlockActionHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n action_id_matcher=block_action_config.action_id,\n block_id_matcher=block_action_config.block_id,\n )\n action_id = matcher_to_str(block_action_config.action_id)\n block_id = matcher_to_str(block_action_config.block_id)\n key = f\"{fq_fn_name}-{action_id}-{block_id}\"\n self._registered_actions.block_actions[key] = handler\n\n def _register_modal_handler(\n self,\n type_: Literal[\"modal\", \"modal_closed\"],\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n modal_config: ModalConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n logger.debug(\"signature of modal handler\", signature=signature, function=fq_fn_name)\n handler = ModalHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n callback_id_matcher=modal_config.callback_id,\n is_generator=modal_config.is_generator,\n )\n key = f\"{fq_fn_name}-{matcher_to_str(modal_config.callback_id)}\"\n getattr(self._registered_actions, type_)[key] = handler\n\n @staticmethod\n def _parse_human_help(doc: str) -> HumanHelp:\n summary = doc.splitlines()[0].split(\":\")\n if len(summary) > 1:\n command = summary[0].strip()\n cmd_help = summary[1].strip()\n else:\n command = \"??\"\n cmd_help = summary[0].strip()\n return HumanHelp(command=command, help=cmd_help)\n\n @staticmethod\n def _parse_robot_help(matcher_config: MatcherConfig, action: str) -> str:\n handle_message_changed_suffix = \" [includes changed messages]\" if matcher_config.handle_changed_message else \"\"\n if action == \"respond_to\":\n return f\"@botname {matcher_config.regex.pattern}{handle_message_changed_suffix}\"\n else:\n return f\"{matcher_config.regex.pattern}{handle_message_changed_suffix}\"\n\n async def run(self) -> None:\n await self._setup()\n assert self._settings is not None\n if self._client is None:\n logger.error(\"Slack client not initialized!\")\n sys.exit(1)\n\n bot_id = self._client.bot_info[\"user_id\"]\n bot_name = self._client.bot_info[\"name\"]\n\n if self._settings.get(\"LOGLEVEL\", \"ERROR\").upper() == \"DEBUG\":\n self._client.register_handler(log_request)\n\n message_handler = create_message_handler(\n self._registered_actions, self._settings, bot_id, bot_name, self._client\n )\n generic_event_handler = create_generic_event_handler(self._registered_actions)\n slash_command_handler = create_slash_command_handler(self._registered_actions, self._client)\n block_action_handler = create_interactive_handler(self._registered_actions, self._client)\n\n self._client.register_handler(message_handler)\n self._client.register_handler(generic_event_handler)\n self._client.register_handler(slash_command_handler)\n self._client.register_handler(block_action_handler)\n # Establish a WebSocket connection to the Socket Mode servers\n await self._socket_mode_client.connect()\n logger.info(\"Connected to Slack\")\n\n self._scheduler.start()\n logger.info(\"Scheduler started\")\n\n # Just not to stop this process\n await asyncio.sleep(float(\"inf\"))\n\n async def close(self) -> None:\n closables = [self._socket_mode_client.close(), self._storage_backend.close()]\n await asyncio.gather(*closables)", "n_imports_parsed": 8, "n_files_resolved": 6, "n_chars_extracted": 15759}, "tests/test_plugin_registration.py::79": {"resolved_imports": ["src/machine/core.py", "src/machine/clients/slack.py", "src/machine/models/core.py", "src/machine/plugins/decorators.py", "src/machine/utils/collections.py", "src/machine/utils/logging.py"], "used_names": ["BlockActionHandler", "CommandHandler", "Machine", "MessageHandler", "ModalHandler", "RegisteredActions", "configure_logging", "pytest", "re"], "enclosing_function": "test_load_and_register_plugins", "extracted_code": "# Source: src/machine/core.py\nclass Machine:\n _socket_mode_client: SocketModeClient\n _client: SlackClient | None\n _storage_backend: MachineBaseStorage\n _settings: CaseInsensitiveDict | None\n _help: Manual\n _registered_actions: RegisteredActions\n _tz: ZoneInfo\n _scheduler: AsyncIOScheduler\n\n def __init__(self, settings: CaseInsensitiveDict | None = None):\n if settings is not None:\n self._settings = settings\n else:\n self._settings = None\n self._help = Manual(human={}, robot={})\n self._registered_actions = RegisteredActions()\n self._client = None\n\n async def _setup(self) -> None:\n logger.info(\"Initializing Slack Machine...\")\n\n found_local_settings = self._load_settings()\n assert self._settings is not None\n configure_logging(self._settings)\n if not found_local_settings:\n logger.warning(\"No local_settings found! Are you sure this is what you want?\")\n else:\n logger.debug(\"Found local settings %s\", self._settings)\n\n # Check if Slack token are present\n if \"SLACK_APP_TOKEN\" not in self._settings:\n logger.error(\"No SLACK_APP_TOKEN found in settings! I need that to work...\")\n sys.exit(1)\n if \"SLACK_BOT_TOKEN\" not in self._settings:\n logger.error(\"No SLACK_BOT_TOKEN found in settings! I need that to work...\")\n sys.exit(1)\n\n # Setup storage\n await self._setup_storage()\n\n # Setup Slack clients\n await self._setup_slack_clients()\n\n # Setup scheduling\n self._scheduler = AsyncIOScheduler(timezone=self._tz)\n\n # Load plugins\n await self._load_plugins()\n logger.debug(\"Registered plugin actions: %s\", self._registered_actions)\n logger.debug(\"Plugin help: %s\", self._help)\n\n def _load_settings(self) -> bool:\n logger.info(\"Loading settings...\")\n if self._settings is not None:\n found_local_settings = True\n else:\n settings_module = os.environ.get(\"SM_SETTINGS_MODULE\", \"local_settings\")\n self._settings, found_local_settings = import_settings(settings_module=settings_module)\n self._tz = ZoneInfo(self._settings[\"TZ\"])\n logger.info(\"Settings loaded!\")\n return found_local_settings\n\n async def _setup_storage(self) -> None:\n assert self._settings is not None\n storage_backend = self._settings.get(\"STORAGE_BACKEND\", \"machine.storage.backends.memory.MemoryStorage\")\n logger.info(\"Initializing storage backend %s...\", storage_backend)\n _, cls = import_string(storage_backend)[0]\n self._storage_backend = cls(self._settings)\n await self._storage_backend.init()\n logger.info(\"Storage backend %s initialized!\", storage_backend)\n\n async def _setup_slack_clients(self) -> None:\n assert self._settings is not None\n # Setup Slack socket mode client\n self._socket_mode_client = SocketModeClient(\n app_token=self._settings[\"SLACK_APP_TOKEN\"],\n web_client=AsyncWebClient(token=self._settings[\"SLACK_BOT_TOKEN\"]),\n proxy=self._settings[\"HTTP_PROXY\"],\n )\n\n # Setup high-level Slack client for plugins\n self._client = SlackClient(self._socket_mode_client, self._tz)\n await self._client.setup()\n\n # TODO: factor out plugin registration in separate class / set of functions\n async def _load_plugins(self) -> None:\n assert self._settings is not None\n if self._client is None:\n logger.error(\"Slack client not initialized!\")\n sys.exit(1)\n logger.debug(\"PLUGINS: %s\", self._settings[\"PLUGINS\"])\n for plugin in self._settings[\"PLUGINS\"]:\n for class_name, cls in import_string(plugin):\n if issubclass(cls, MachineBasePlugin) and cls is not MachineBasePlugin:\n logger.debug(\"Found a Machine plugin: %s\", plugin)\n storage = PluginStorage(class_name, self._storage_backend)\n instance = cls(self._client, self._settings, storage)\n missing_settings = self._register_plugin(class_name, instance)\n if missing_settings:\n logger.warning(\"Error loading plugin %s\", class_name)\n error_msg = f\"The following settings are missing: {', '.join(missing_settings)}\"\n logger.warning(error_msg)\n del instance\n else:\n await instance.init()\n logger.info(\"Plugin %s loaded\", class_name)\n await self._storage_backend.set(\"manual\", dill.dumps(self._help))\n\n def _register_plugin(self, plugin_class_name: str, cls_instance: MachineBasePlugin) -> list[str] | None:\n missing_settings = []\n cls_instance_for_missing_settings = cast(DecoratedPluginFunc, cls_instance)\n missing_settings.extend(self._check_missing_settings(cls_instance_for_missing_settings))\n methods = inspect.getmembers(cls_instance, predicate=inspect.ismethod)\n for _, fn in methods:\n method_for_missing_settings = cast(DecoratedPluginFunc, fn)\n missing_settings.extend(self._check_missing_settings(method_for_missing_settings))\n if missing_settings:\n return missing_settings\n\n class_help = cls_instance.__doc__.splitlines()[0] if cls_instance.__doc__ else plugin_class_name\n self._help.human[class_help] = self._help.human.get(class_help, {})\n self._help.robot[class_help] = self._help.robot.get(class_help, [])\n for name, fn in methods:\n if hasattr(fn, \"metadata\"):\n self._register_plugin_actions(plugin_class_name, fn.metadata, cls_instance, name, fn, class_help)\n return None\n\n def _check_missing_settings(self, fn_or_class: DecoratedPluginFunc) -> list[str]:\n missing_settings = []\n if hasattr(fn_or_class, \"metadata\") and isinstance(fn_or_class.metadata, Metadata):\n for setting in fn_or_class.metadata.required_settings:\n if self._settings is None or setting not in self._settings:\n missing_settings.append(setting.upper())\n return missing_settings\n\n def _register_plugin_actions(\n self,\n plugin_class_name: str,\n metadata: Metadata,\n cls_instance: MachineBasePlugin,\n fn_name: str,\n fn: Callable[..., Awaitable[None]],\n class_help: str,\n ) -> None:\n fq_fn_name = f\"{plugin_class_name}.{fn_name}\"\n if fn.__doc__:\n self._help.human[class_help][fq_fn_name] = self._parse_human_help(fn.__doc__)\n for matcher_config in metadata.plugin_actions.listen_to:\n self._register_message_handler(\n type_=\"listen_to\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n matcher_config=matcher_config,\n class_help=class_help,\n )\n for matcher_config in metadata.plugin_actions.respond_to:\n self._register_message_handler(\n type_=\"respond_to\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n matcher_config=matcher_config,\n class_help=class_help,\n )\n for event in metadata.plugin_actions.process:\n self._registered_actions.process[event] = self._registered_actions.process.get(event, {})\n key = f\"{fq_fn_name}-{event}\"\n self._registered_actions.process[event][key] = fn\n for command_config in metadata.plugin_actions.commands:\n self._register_command_handler(\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n command_config=command_config,\n class_help=class_help,\n )\n for block_action_config in metadata.plugin_actions.actions:\n self._register_block_action_handler(\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n block_action_config=block_action_config,\n class_help=class_help,\n )\n for modal_config in metadata.plugin_actions.modal_submissions:\n self._register_modal_handler(\n type_=\"modal\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n modal_config=modal_config,\n class_help=class_help,\n )\n for modal_config in metadata.plugin_actions.modal_closures:\n self._register_modal_handler(\n type_=\"modal_closed\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n modal_config=modal_config,\n class_help=class_help,\n )\n\n if metadata.plugin_actions.schedule is not None:\n self._scheduler.add_job(\n fn,\n trigger=\"cron\",\n args=[],\n id=fq_fn_name,\n replace_existing=True,\n **metadata.plugin_actions.schedule,\n )\n\n def _register_message_handler(\n self,\n type_: Literal[\"listen_to\", \"respond_to\"],\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n matcher_config: MatcherConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n handler = MessageHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n regex=matcher_config.regex,\n handle_message_changed=matcher_config.handle_changed_message,\n )\n key = f\"{fq_fn_name}-{matcher_config.regex.pattern}\"\n getattr(self._registered_actions, type_)[key] = handler\n self._help.robot[class_help].append(self._parse_robot_help(matcher_config, type_))\n\n def _register_command_handler(\n self,\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n command_config: CommandConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n logger.debug(\"signature of command handler\", signature=signature, function=fq_fn_name)\n handler = CommandHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n command=command_config.command,\n is_generator=command_config.is_generator,\n )\n command = command_config.command\n if command in self._registered_actions.command:\n logger.warning(\"command was already defined, previous handler will be overwritten!\", command=command)\n self._registered_actions.command[command] = handler\n # TODO: add to help\n\n def _register_block_action_handler(\n self,\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n block_action_config: ActionConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n logger.debug(\"signature of block action handler\", signature=signature, function=fq_fn_name)\n handler = BlockActionHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n action_id_matcher=block_action_config.action_id,\n block_id_matcher=block_action_config.block_id,\n )\n action_id = matcher_to_str(block_action_config.action_id)\n block_id = matcher_to_str(block_action_config.block_id)\n key = f\"{fq_fn_name}-{action_id}-{block_id}\"\n self._registered_actions.block_actions[key] = handler\n\n def _register_modal_handler(\n self,\n type_: Literal[\"modal\", \"modal_closed\"],\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n modal_config: ModalConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n logger.debug(\"signature of modal handler\", signature=signature, function=fq_fn_name)\n handler = ModalHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n callback_id_matcher=modal_config.callback_id,\n is_generator=modal_config.is_generator,\n )\n key = f\"{fq_fn_name}-{matcher_to_str(modal_config.callback_id)}\"\n getattr(self._registered_actions, type_)[key] = handler\n\n @staticmethod\n def _parse_human_help(doc: str) -> HumanHelp:\n summary = doc.splitlines()[0].split(\":\")\n if len(summary) > 1:\n command = summary[0].strip()\n cmd_help = summary[1].strip()\n else:\n command = \"??\"\n cmd_help = summary[0].strip()\n return HumanHelp(command=command, help=cmd_help)\n\n @staticmethod\n def _parse_robot_help(matcher_config: MatcherConfig, action: str) -> str:\n handle_message_changed_suffix = \" [includes changed messages]\" if matcher_config.handle_changed_message else \"\"\n if action == \"respond_to\":\n return f\"@botname {matcher_config.regex.pattern}{handle_message_changed_suffix}\"\n else:\n return f\"{matcher_config.regex.pattern}{handle_message_changed_suffix}\"\n\n async def run(self) -> None:\n await self._setup()\n assert self._settings is not None\n if self._client is None:\n logger.error(\"Slack client not initialized!\")\n sys.exit(1)\n\n bot_id = self._client.bot_info[\"user_id\"]\n bot_name = self._client.bot_info[\"name\"]\n\n if self._settings.get(\"LOGLEVEL\", \"ERROR\").upper() == \"DEBUG\":\n self._client.register_handler(log_request)\n\n message_handler = create_message_handler(\n self._registered_actions, self._settings, bot_id, bot_name, self._client\n )\n generic_event_handler = create_generic_event_handler(self._registered_actions)\n slash_command_handler = create_slash_command_handler(self._registered_actions, self._client)\n block_action_handler = create_interactive_handler(self._registered_actions, self._client)\n\n self._client.register_handler(message_handler)\n self._client.register_handler(generic_event_handler)\n self._client.register_handler(slash_command_handler)\n self._client.register_handler(block_action_handler)\n # Establish a WebSocket connection to the Socket Mode servers\n await self._socket_mode_client.connect()\n logger.info(\"Connected to Slack\")\n\n self._scheduler.start()\n logger.info(\"Scheduler started\")\n\n # Just not to stop this process\n await asyncio.sleep(float(\"inf\"))\n\n async def close(self) -> None:\n closables = [self._socket_mode_client.close(), self._storage_backend.close()]\n await asyncio.gather(*closables)\n\n\n# Source: src/machine/models/core.py\nclass MessageHandler:\n class_: MachineBasePlugin\n class_name: str\n function: Callable[..., Awaitable[None]]\n function_signature: Signature\n regex: re.Pattern[str]\n handle_message_changed: bool\n\nclass CommandHandler:\n class_: MachineBasePlugin\n class_name: str\n function: Callable[..., Awaitable[None] | AsyncGenerator[dict | JsonObject | str, None]]\n function_signature: Signature\n command: str\n is_generator: bool\n\nclass BlockActionHandler:\n class_: MachineBasePlugin\n class_name: str\n function: Callable[..., Awaitable[None]]\n function_signature: Signature\n action_id_matcher: Union[re.Pattern[str], str, None]\n block_id_matcher: Union[re.Pattern[str], str, None]\n\nclass ModalHandler:\n class_: MachineBasePlugin\n class_name: str\n function: Callable[..., Awaitable[None]]\n function_signature: Signature\n callback_id_matcher: Union[re.Pattern[str], str]\n is_generator: bool\n\nclass RegisteredActions:\n listen_to: dict[str, MessageHandler] = field(default_factory=dict)\n respond_to: dict[str, MessageHandler] = field(default_factory=dict)\n process: dict[str, dict[str, Callable[[dict[str, Any]], Awaitable[None]]]] = field(default_factory=dict)\n command: dict[str, CommandHandler] = field(default_factory=dict)\n block_actions: dict[str, BlockActionHandler] = field(default_factory=dict)\n modal: dict[str, ModalHandler] = field(default_factory=dict)\n modal_closed: dict[str, ModalHandler] = field(default_factory=dict)\n\n\n# Source: src/machine/utils/logging.py\ndef configure_logging(settings: Mapping[str, Any]) -> None:\n \"\"\"\n Configure logging with structlog. This function will configure structlog to use the right processors to add\n revelant metadata to the logs, such as timestamp, source file, line number, and function name.\n Next to that, it will configure all standard logging handlers to use structlog for formatting.\n :return: None\n \"\"\"\n\n # These processors are used both by the logs generated through structlog as well as the logs generated through\n # the stdlib logging module (incl. logs from third-party packages)\n shared_processors: list[Processor] = [\n structlog.contextvars.merge_contextvars,\n structlog.stdlib.add_logger_name,\n structlog.stdlib.add_log_level,\n structlog.stdlib.PositionalArgumentsFormatter(),\n structlog.processors.TimeStamper(fmt=\"iso\"),\n structlog.processors.StackInfoRenderer(),\n structlog.processors.format_exc_info,\n structlog.processors.UnicodeDecoder(),\n structlog.processors.CallsiteParameterAdder([\n CallsiteParameter.FILENAME,\n CallsiteParameter.FUNC_NAME,\n CallsiteParameter.LINENO,\n ]),\n ]\n # Configure structlog itself\n structlog.configure(\n processors=shared_processors + [structlog.stdlib.ProcessorFormatter.wrap_for_formatter],\n context_class=dict,\n wrapper_class=structlog.stdlib.BoundLogger,\n logger_factory=structlog.stdlib.LoggerFactory(),\n cache_logger_on_first_use=True,\n )\n # Create a formatter. Use Console renderer in terminal and JSON renderer when running in container\n renderer: Processor\n if sys.stdout.isatty(): # noqa: SIM108 (doesn't work with mypy)\n renderer = structlog.dev.ConsoleRenderer()\n else:\n renderer = structlog.processors.JSONRenderer()\n\n formatter = structlog.stdlib.ProcessorFormatter(\n foreign_pre_chain=shared_processors,\n processors=[\n structlog.stdlib.ProcessorFormatter.remove_processors_meta,\n renderer,\n ],\n )\n # All logging is going to be rendered by the stdlib logging module\n handler = logging.StreamHandler()\n # Use OUR `ProcessorFormatter` to format all `logging` entries.\n handler.setFormatter(formatter)\n root_logger = logging.getLogger()\n # We want to get rid of their pre-configured log handlers\n for h in root_logger.handlers:\n root_logger.removeHandler(h)\n root_logger.addHandler(handler)\n level_str = settings.get(\"LOGLEVEL\", \"ERROR\")\n # Get level as int so we can compare it\n level = logging.getLevelName(level_str)\n root_logger.setLevel(level)\n if level < logging.INFO:\n logging.getLogger(\"slack_sdk.socket_mode.aiohttp\").setLevel(logging.INFO)\n logging.getLogger(\"slack_sdk.web.async_base_client\").setLevel(logging.INFO)", "n_imports_parsed": 8, "n_files_resolved": 6, "n_chars_extracted": 20224}, "tests/test_plugin_registration.py::153": {"resolved_imports": ["src/machine/core.py", "src/machine/clients/slack.py", "src/machine/models/core.py", "src/machine/plugins/decorators.py", "src/machine/utils/collections.py", "src/machine/utils/logging.py"], "used_names": ["Machine"], "enclosing_function": "test_required_settings", "extracted_code": "# Source: src/machine/core.py\nclass Machine:\n _socket_mode_client: SocketModeClient\n _client: SlackClient | None\n _storage_backend: MachineBaseStorage\n _settings: CaseInsensitiveDict | None\n _help: Manual\n _registered_actions: RegisteredActions\n _tz: ZoneInfo\n _scheduler: AsyncIOScheduler\n\n def __init__(self, settings: CaseInsensitiveDict | None = None):\n if settings is not None:\n self._settings = settings\n else:\n self._settings = None\n self._help = Manual(human={}, robot={})\n self._registered_actions = RegisteredActions()\n self._client = None\n\n async def _setup(self) -> None:\n logger.info(\"Initializing Slack Machine...\")\n\n found_local_settings = self._load_settings()\n assert self._settings is not None\n configure_logging(self._settings)\n if not found_local_settings:\n logger.warning(\"No local_settings found! Are you sure this is what you want?\")\n else:\n logger.debug(\"Found local settings %s\", self._settings)\n\n # Check if Slack token are present\n if \"SLACK_APP_TOKEN\" not in self._settings:\n logger.error(\"No SLACK_APP_TOKEN found in settings! I need that to work...\")\n sys.exit(1)\n if \"SLACK_BOT_TOKEN\" not in self._settings:\n logger.error(\"No SLACK_BOT_TOKEN found in settings! I need that to work...\")\n sys.exit(1)\n\n # Setup storage\n await self._setup_storage()\n\n # Setup Slack clients\n await self._setup_slack_clients()\n\n # Setup scheduling\n self._scheduler = AsyncIOScheduler(timezone=self._tz)\n\n # Load plugins\n await self._load_plugins()\n logger.debug(\"Registered plugin actions: %s\", self._registered_actions)\n logger.debug(\"Plugin help: %s\", self._help)\n\n def _load_settings(self) -> bool:\n logger.info(\"Loading settings...\")\n if self._settings is not None:\n found_local_settings = True\n else:\n settings_module = os.environ.get(\"SM_SETTINGS_MODULE\", \"local_settings\")\n self._settings, found_local_settings = import_settings(settings_module=settings_module)\n self._tz = ZoneInfo(self._settings[\"TZ\"])\n logger.info(\"Settings loaded!\")\n return found_local_settings\n\n async def _setup_storage(self) -> None:\n assert self._settings is not None\n storage_backend = self._settings.get(\"STORAGE_BACKEND\", \"machine.storage.backends.memory.MemoryStorage\")\n logger.info(\"Initializing storage backend %s...\", storage_backend)\n _, cls = import_string(storage_backend)[0]\n self._storage_backend = cls(self._settings)\n await self._storage_backend.init()\n logger.info(\"Storage backend %s initialized!\", storage_backend)\n\n async def _setup_slack_clients(self) -> None:\n assert self._settings is not None\n # Setup Slack socket mode client\n self._socket_mode_client = SocketModeClient(\n app_token=self._settings[\"SLACK_APP_TOKEN\"],\n web_client=AsyncWebClient(token=self._settings[\"SLACK_BOT_TOKEN\"]),\n proxy=self._settings[\"HTTP_PROXY\"],\n )\n\n # Setup high-level Slack client for plugins\n self._client = SlackClient(self._socket_mode_client, self._tz)\n await self._client.setup()\n\n # TODO: factor out plugin registration in separate class / set of functions\n async def _load_plugins(self) -> None:\n assert self._settings is not None\n if self._client is None:\n logger.error(\"Slack client not initialized!\")\n sys.exit(1)\n logger.debug(\"PLUGINS: %s\", self._settings[\"PLUGINS\"])\n for plugin in self._settings[\"PLUGINS\"]:\n for class_name, cls in import_string(plugin):\n if issubclass(cls, MachineBasePlugin) and cls is not MachineBasePlugin:\n logger.debug(\"Found a Machine plugin: %s\", plugin)\n storage = PluginStorage(class_name, self._storage_backend)\n instance = cls(self._client, self._settings, storage)\n missing_settings = self._register_plugin(class_name, instance)\n if missing_settings:\n logger.warning(\"Error loading plugin %s\", class_name)\n error_msg = f\"The following settings are missing: {', '.join(missing_settings)}\"\n logger.warning(error_msg)\n del instance\n else:\n await instance.init()\n logger.info(\"Plugin %s loaded\", class_name)\n await self._storage_backend.set(\"manual\", dill.dumps(self._help))\n\n def _register_plugin(self, plugin_class_name: str, cls_instance: MachineBasePlugin) -> list[str] | None:\n missing_settings = []\n cls_instance_for_missing_settings = cast(DecoratedPluginFunc, cls_instance)\n missing_settings.extend(self._check_missing_settings(cls_instance_for_missing_settings))\n methods = inspect.getmembers(cls_instance, predicate=inspect.ismethod)\n for _, fn in methods:\n method_for_missing_settings = cast(DecoratedPluginFunc, fn)\n missing_settings.extend(self._check_missing_settings(method_for_missing_settings))\n if missing_settings:\n return missing_settings\n\n class_help = cls_instance.__doc__.splitlines()[0] if cls_instance.__doc__ else plugin_class_name\n self._help.human[class_help] = self._help.human.get(class_help, {})\n self._help.robot[class_help] = self._help.robot.get(class_help, [])\n for name, fn in methods:\n if hasattr(fn, \"metadata\"):\n self._register_plugin_actions(plugin_class_name, fn.metadata, cls_instance, name, fn, class_help)\n return None\n\n def _check_missing_settings(self, fn_or_class: DecoratedPluginFunc) -> list[str]:\n missing_settings = []\n if hasattr(fn_or_class, \"metadata\") and isinstance(fn_or_class.metadata, Metadata):\n for setting in fn_or_class.metadata.required_settings:\n if self._settings is None or setting not in self._settings:\n missing_settings.append(setting.upper())\n return missing_settings\n\n def _register_plugin_actions(\n self,\n plugin_class_name: str,\n metadata: Metadata,\n cls_instance: MachineBasePlugin,\n fn_name: str,\n fn: Callable[..., Awaitable[None]],\n class_help: str,\n ) -> None:\n fq_fn_name = f\"{plugin_class_name}.{fn_name}\"\n if fn.__doc__:\n self._help.human[class_help][fq_fn_name] = self._parse_human_help(fn.__doc__)\n for matcher_config in metadata.plugin_actions.listen_to:\n self._register_message_handler(\n type_=\"listen_to\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n matcher_config=matcher_config,\n class_help=class_help,\n )\n for matcher_config in metadata.plugin_actions.respond_to:\n self._register_message_handler(\n type_=\"respond_to\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n matcher_config=matcher_config,\n class_help=class_help,\n )\n for event in metadata.plugin_actions.process:\n self._registered_actions.process[event] = self._registered_actions.process.get(event, {})\n key = f\"{fq_fn_name}-{event}\"\n self._registered_actions.process[event][key] = fn\n for command_config in metadata.plugin_actions.commands:\n self._register_command_handler(\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n command_config=command_config,\n class_help=class_help,\n )\n for block_action_config in metadata.plugin_actions.actions:\n self._register_block_action_handler(\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n block_action_config=block_action_config,\n class_help=class_help,\n )\n for modal_config in metadata.plugin_actions.modal_submissions:\n self._register_modal_handler(\n type_=\"modal\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n modal_config=modal_config,\n class_help=class_help,\n )\n for modal_config in metadata.plugin_actions.modal_closures:\n self._register_modal_handler(\n type_=\"modal_closed\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n modal_config=modal_config,\n class_help=class_help,\n )\n\n if metadata.plugin_actions.schedule is not None:\n self._scheduler.add_job(\n fn,\n trigger=\"cron\",\n args=[],\n id=fq_fn_name,\n replace_existing=True,\n **metadata.plugin_actions.schedule,\n )\n\n def _register_message_handler(\n self,\n type_: Literal[\"listen_to\", \"respond_to\"],\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n matcher_config: MatcherConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n handler = MessageHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n regex=matcher_config.regex,\n handle_message_changed=matcher_config.handle_changed_message,\n )\n key = f\"{fq_fn_name}-{matcher_config.regex.pattern}\"\n getattr(self._registered_actions, type_)[key] = handler\n self._help.robot[class_help].append(self._parse_robot_help(matcher_config, type_))\n\n def _register_command_handler(\n self,\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n command_config: CommandConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n logger.debug(\"signature of command handler\", signature=signature, function=fq_fn_name)\n handler = CommandHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n command=command_config.command,\n is_generator=command_config.is_generator,\n )\n command = command_config.command\n if command in self._registered_actions.command:\n logger.warning(\"command was already defined, previous handler will be overwritten!\", command=command)\n self._registered_actions.command[command] = handler\n # TODO: add to help\n\n def _register_block_action_handler(\n self,\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n block_action_config: ActionConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n logger.debug(\"signature of block action handler\", signature=signature, function=fq_fn_name)\n handler = BlockActionHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n action_id_matcher=block_action_config.action_id,\n block_id_matcher=block_action_config.block_id,\n )\n action_id = matcher_to_str(block_action_config.action_id)\n block_id = matcher_to_str(block_action_config.block_id)\n key = f\"{fq_fn_name}-{action_id}-{block_id}\"\n self._registered_actions.block_actions[key] = handler\n\n def _register_modal_handler(\n self,\n type_: Literal[\"modal\", \"modal_closed\"],\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n modal_config: ModalConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n logger.debug(\"signature of modal handler\", signature=signature, function=fq_fn_name)\n handler = ModalHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n callback_id_matcher=modal_config.callback_id,\n is_generator=modal_config.is_generator,\n )\n key = f\"{fq_fn_name}-{matcher_to_str(modal_config.callback_id)}\"\n getattr(self._registered_actions, type_)[key] = handler\n\n @staticmethod\n def _parse_human_help(doc: str) -> HumanHelp:\n summary = doc.splitlines()[0].split(\":\")\n if len(summary) > 1:\n command = summary[0].strip()\n cmd_help = summary[1].strip()\n else:\n command = \"??\"\n cmd_help = summary[0].strip()\n return HumanHelp(command=command, help=cmd_help)\n\n @staticmethod\n def _parse_robot_help(matcher_config: MatcherConfig, action: str) -> str:\n handle_message_changed_suffix = \" [includes changed messages]\" if matcher_config.handle_changed_message else \"\"\n if action == \"respond_to\":\n return f\"@botname {matcher_config.regex.pattern}{handle_message_changed_suffix}\"\n else:\n return f\"{matcher_config.regex.pattern}{handle_message_changed_suffix}\"\n\n async def run(self) -> None:\n await self._setup()\n assert self._settings is not None\n if self._client is None:\n logger.error(\"Slack client not initialized!\")\n sys.exit(1)\n\n bot_id = self._client.bot_info[\"user_id\"]\n bot_name = self._client.bot_info[\"name\"]\n\n if self._settings.get(\"LOGLEVEL\", \"ERROR\").upper() == \"DEBUG\":\n self._client.register_handler(log_request)\n\n message_handler = create_message_handler(\n self._registered_actions, self._settings, bot_id, bot_name, self._client\n )\n generic_event_handler = create_generic_event_handler(self._registered_actions)\n slash_command_handler = create_slash_command_handler(self._registered_actions, self._client)\n block_action_handler = create_interactive_handler(self._registered_actions, self._client)\n\n self._client.register_handler(message_handler)\n self._client.register_handler(generic_event_handler)\n self._client.register_handler(slash_command_handler)\n self._client.register_handler(block_action_handler)\n # Establish a WebSocket connection to the Socket Mode servers\n await self._socket_mode_client.connect()\n logger.info(\"Connected to Slack\")\n\n self._scheduler.start()\n logger.info(\"Scheduler started\")\n\n # Just not to stop this process\n await asyncio.sleep(float(\"inf\"))\n\n async def close(self) -> None:\n closables = [self._socket_mode_client.close(), self._storage_backend.close()]\n await asyncio.gather(*closables)", "n_imports_parsed": 8, "n_files_resolved": 6, "n_chars_extracted": 15759}, "tests/test_plugin_registration.py::98": {"resolved_imports": ["src/machine/core.py", "src/machine/clients/slack.py", "src/machine/models/core.py", "src/machine/plugins/decorators.py", "src/machine/utils/collections.py", "src/machine/utils/logging.py"], "used_names": ["BlockActionHandler", "CommandHandler", "Machine", "MessageHandler", "ModalHandler", "RegisteredActions", "configure_logging", "pytest", "re"], "enclosing_function": "test_load_and_register_plugins", "extracted_code": "# Source: src/machine/core.py\nclass Machine:\n _socket_mode_client: SocketModeClient\n _client: SlackClient | None\n _storage_backend: MachineBaseStorage\n _settings: CaseInsensitiveDict | None\n _help: Manual\n _registered_actions: RegisteredActions\n _tz: ZoneInfo\n _scheduler: AsyncIOScheduler\n\n def __init__(self, settings: CaseInsensitiveDict | None = None):\n if settings is not None:\n self._settings = settings\n else:\n self._settings = None\n self._help = Manual(human={}, robot={})\n self._registered_actions = RegisteredActions()\n self._client = None\n\n async def _setup(self) -> None:\n logger.info(\"Initializing Slack Machine...\")\n\n found_local_settings = self._load_settings()\n assert self._settings is not None\n configure_logging(self._settings)\n if not found_local_settings:\n logger.warning(\"No local_settings found! Are you sure this is what you want?\")\n else:\n logger.debug(\"Found local settings %s\", self._settings)\n\n # Check if Slack token are present\n if \"SLACK_APP_TOKEN\" not in self._settings:\n logger.error(\"No SLACK_APP_TOKEN found in settings! I need that to work...\")\n sys.exit(1)\n if \"SLACK_BOT_TOKEN\" not in self._settings:\n logger.error(\"No SLACK_BOT_TOKEN found in settings! I need that to work...\")\n sys.exit(1)\n\n # Setup storage\n await self._setup_storage()\n\n # Setup Slack clients\n await self._setup_slack_clients()\n\n # Setup scheduling\n self._scheduler = AsyncIOScheduler(timezone=self._tz)\n\n # Load plugins\n await self._load_plugins()\n logger.debug(\"Registered plugin actions: %s\", self._registered_actions)\n logger.debug(\"Plugin help: %s\", self._help)\n\n def _load_settings(self) -> bool:\n logger.info(\"Loading settings...\")\n if self._settings is not None:\n found_local_settings = True\n else:\n settings_module = os.environ.get(\"SM_SETTINGS_MODULE\", \"local_settings\")\n self._settings, found_local_settings = import_settings(settings_module=settings_module)\n self._tz = ZoneInfo(self._settings[\"TZ\"])\n logger.info(\"Settings loaded!\")\n return found_local_settings\n\n async def _setup_storage(self) -> None:\n assert self._settings is not None\n storage_backend = self._settings.get(\"STORAGE_BACKEND\", \"machine.storage.backends.memory.MemoryStorage\")\n logger.info(\"Initializing storage backend %s...\", storage_backend)\n _, cls = import_string(storage_backend)[0]\n self._storage_backend = cls(self._settings)\n await self._storage_backend.init()\n logger.info(\"Storage backend %s initialized!\", storage_backend)\n\n async def _setup_slack_clients(self) -> None:\n assert self._settings is not None\n # Setup Slack socket mode client\n self._socket_mode_client = SocketModeClient(\n app_token=self._settings[\"SLACK_APP_TOKEN\"],\n web_client=AsyncWebClient(token=self._settings[\"SLACK_BOT_TOKEN\"]),\n proxy=self._settings[\"HTTP_PROXY\"],\n )\n\n # Setup high-level Slack client for plugins\n self._client = SlackClient(self._socket_mode_client, self._tz)\n await self._client.setup()\n\n # TODO: factor out plugin registration in separate class / set of functions\n async def _load_plugins(self) -> None:\n assert self._settings is not None\n if self._client is None:\n logger.error(\"Slack client not initialized!\")\n sys.exit(1)\n logger.debug(\"PLUGINS: %s\", self._settings[\"PLUGINS\"])\n for plugin in self._settings[\"PLUGINS\"]:\n for class_name, cls in import_string(plugin):\n if issubclass(cls, MachineBasePlugin) and cls is not MachineBasePlugin:\n logger.debug(\"Found a Machine plugin: %s\", plugin)\n storage = PluginStorage(class_name, self._storage_backend)\n instance = cls(self._client, self._settings, storage)\n missing_settings = self._register_plugin(class_name, instance)\n if missing_settings:\n logger.warning(\"Error loading plugin %s\", class_name)\n error_msg = f\"The following settings are missing: {', '.join(missing_settings)}\"\n logger.warning(error_msg)\n del instance\n else:\n await instance.init()\n logger.info(\"Plugin %s loaded\", class_name)\n await self._storage_backend.set(\"manual\", dill.dumps(self._help))\n\n def _register_plugin(self, plugin_class_name: str, cls_instance: MachineBasePlugin) -> list[str] | None:\n missing_settings = []\n cls_instance_for_missing_settings = cast(DecoratedPluginFunc, cls_instance)\n missing_settings.extend(self._check_missing_settings(cls_instance_for_missing_settings))\n methods = inspect.getmembers(cls_instance, predicate=inspect.ismethod)\n for _, fn in methods:\n method_for_missing_settings = cast(DecoratedPluginFunc, fn)\n missing_settings.extend(self._check_missing_settings(method_for_missing_settings))\n if missing_settings:\n return missing_settings\n\n class_help = cls_instance.__doc__.splitlines()[0] if cls_instance.__doc__ else plugin_class_name\n self._help.human[class_help] = self._help.human.get(class_help, {})\n self._help.robot[class_help] = self._help.robot.get(class_help, [])\n for name, fn in methods:\n if hasattr(fn, \"metadata\"):\n self._register_plugin_actions(plugin_class_name, fn.metadata, cls_instance, name, fn, class_help)\n return None\n\n def _check_missing_settings(self, fn_or_class: DecoratedPluginFunc) -> list[str]:\n missing_settings = []\n if hasattr(fn_or_class, \"metadata\") and isinstance(fn_or_class.metadata, Metadata):\n for setting in fn_or_class.metadata.required_settings:\n if self._settings is None or setting not in self._settings:\n missing_settings.append(setting.upper())\n return missing_settings\n\n def _register_plugin_actions(\n self,\n plugin_class_name: str,\n metadata: Metadata,\n cls_instance: MachineBasePlugin,\n fn_name: str,\n fn: Callable[..., Awaitable[None]],\n class_help: str,\n ) -> None:\n fq_fn_name = f\"{plugin_class_name}.{fn_name}\"\n if fn.__doc__:\n self._help.human[class_help][fq_fn_name] = self._parse_human_help(fn.__doc__)\n for matcher_config in metadata.plugin_actions.listen_to:\n self._register_message_handler(\n type_=\"listen_to\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n matcher_config=matcher_config,\n class_help=class_help,\n )\n for matcher_config in metadata.plugin_actions.respond_to:\n self._register_message_handler(\n type_=\"respond_to\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n matcher_config=matcher_config,\n class_help=class_help,\n )\n for event in metadata.plugin_actions.process:\n self._registered_actions.process[event] = self._registered_actions.process.get(event, {})\n key = f\"{fq_fn_name}-{event}\"\n self._registered_actions.process[event][key] = fn\n for command_config in metadata.plugin_actions.commands:\n self._register_command_handler(\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n command_config=command_config,\n class_help=class_help,\n )\n for block_action_config in metadata.plugin_actions.actions:\n self._register_block_action_handler(\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n block_action_config=block_action_config,\n class_help=class_help,\n )\n for modal_config in metadata.plugin_actions.modal_submissions:\n self._register_modal_handler(\n type_=\"modal\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n modal_config=modal_config,\n class_help=class_help,\n )\n for modal_config in metadata.plugin_actions.modal_closures:\n self._register_modal_handler(\n type_=\"modal_closed\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n modal_config=modal_config,\n class_help=class_help,\n )\n\n if metadata.plugin_actions.schedule is not None:\n self._scheduler.add_job(\n fn,\n trigger=\"cron\",\n args=[],\n id=fq_fn_name,\n replace_existing=True,\n **metadata.plugin_actions.schedule,\n )\n\n def _register_message_handler(\n self,\n type_: Literal[\"listen_to\", \"respond_to\"],\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n matcher_config: MatcherConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n handler = MessageHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n regex=matcher_config.regex,\n handle_message_changed=matcher_config.handle_changed_message,\n )\n key = f\"{fq_fn_name}-{matcher_config.regex.pattern}\"\n getattr(self._registered_actions, type_)[key] = handler\n self._help.robot[class_help].append(self._parse_robot_help(matcher_config, type_))\n\n def _register_command_handler(\n self,\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n command_config: CommandConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n logger.debug(\"signature of command handler\", signature=signature, function=fq_fn_name)\n handler = CommandHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n command=command_config.command,\n is_generator=command_config.is_generator,\n )\n command = command_config.command\n if command in self._registered_actions.command:\n logger.warning(\"command was already defined, previous handler will be overwritten!\", command=command)\n self._registered_actions.command[command] = handler\n # TODO: add to help\n\n def _register_block_action_handler(\n self,\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n block_action_config: ActionConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n logger.debug(\"signature of block action handler\", signature=signature, function=fq_fn_name)\n handler = BlockActionHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n action_id_matcher=block_action_config.action_id,\n block_id_matcher=block_action_config.block_id,\n )\n action_id = matcher_to_str(block_action_config.action_id)\n block_id = matcher_to_str(block_action_config.block_id)\n key = f\"{fq_fn_name}-{action_id}-{block_id}\"\n self._registered_actions.block_actions[key] = handler\n\n def _register_modal_handler(\n self,\n type_: Literal[\"modal\", \"modal_closed\"],\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n modal_config: ModalConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n logger.debug(\"signature of modal handler\", signature=signature, function=fq_fn_name)\n handler = ModalHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n callback_id_matcher=modal_config.callback_id,\n is_generator=modal_config.is_generator,\n )\n key = f\"{fq_fn_name}-{matcher_to_str(modal_config.callback_id)}\"\n getattr(self._registered_actions, type_)[key] = handler\n\n @staticmethod\n def _parse_human_help(doc: str) -> HumanHelp:\n summary = doc.splitlines()[0].split(\":\")\n if len(summary) > 1:\n command = summary[0].strip()\n cmd_help = summary[1].strip()\n else:\n command = \"??\"\n cmd_help = summary[0].strip()\n return HumanHelp(command=command, help=cmd_help)\n\n @staticmethod\n def _parse_robot_help(matcher_config: MatcherConfig, action: str) -> str:\n handle_message_changed_suffix = \" [includes changed messages]\" if matcher_config.handle_changed_message else \"\"\n if action == \"respond_to\":\n return f\"@botname {matcher_config.regex.pattern}{handle_message_changed_suffix}\"\n else:\n return f\"{matcher_config.regex.pattern}{handle_message_changed_suffix}\"\n\n async def run(self) -> None:\n await self._setup()\n assert self._settings is not None\n if self._client is None:\n logger.error(\"Slack client not initialized!\")\n sys.exit(1)\n\n bot_id = self._client.bot_info[\"user_id\"]\n bot_name = self._client.bot_info[\"name\"]\n\n if self._settings.get(\"LOGLEVEL\", \"ERROR\").upper() == \"DEBUG\":\n self._client.register_handler(log_request)\n\n message_handler = create_message_handler(\n self._registered_actions, self._settings, bot_id, bot_name, self._client\n )\n generic_event_handler = create_generic_event_handler(self._registered_actions)\n slash_command_handler = create_slash_command_handler(self._registered_actions, self._client)\n block_action_handler = create_interactive_handler(self._registered_actions, self._client)\n\n self._client.register_handler(message_handler)\n self._client.register_handler(generic_event_handler)\n self._client.register_handler(slash_command_handler)\n self._client.register_handler(block_action_handler)\n # Establish a WebSocket connection to the Socket Mode servers\n await self._socket_mode_client.connect()\n logger.info(\"Connected to Slack\")\n\n self._scheduler.start()\n logger.info(\"Scheduler started\")\n\n # Just not to stop this process\n await asyncio.sleep(float(\"inf\"))\n\n async def close(self) -> None:\n closables = [self._socket_mode_client.close(), self._storage_backend.close()]\n await asyncio.gather(*closables)\n\n\n# Source: src/machine/models/core.py\nclass MessageHandler:\n class_: MachineBasePlugin\n class_name: str\n function: Callable[..., Awaitable[None]]\n function_signature: Signature\n regex: re.Pattern[str]\n handle_message_changed: bool\n\nclass CommandHandler:\n class_: MachineBasePlugin\n class_name: str\n function: Callable[..., Awaitable[None] | AsyncGenerator[dict | JsonObject | str, None]]\n function_signature: Signature\n command: str\n is_generator: bool\n\nclass BlockActionHandler:\n class_: MachineBasePlugin\n class_name: str\n function: Callable[..., Awaitable[None]]\n function_signature: Signature\n action_id_matcher: Union[re.Pattern[str], str, None]\n block_id_matcher: Union[re.Pattern[str], str, None]\n\nclass ModalHandler:\n class_: MachineBasePlugin\n class_name: str\n function: Callable[..., Awaitable[None]]\n function_signature: Signature\n callback_id_matcher: Union[re.Pattern[str], str]\n is_generator: bool\n\nclass RegisteredActions:\n listen_to: dict[str, MessageHandler] = field(default_factory=dict)\n respond_to: dict[str, MessageHandler] = field(default_factory=dict)\n process: dict[str, dict[str, Callable[[dict[str, Any]], Awaitable[None]]]] = field(default_factory=dict)\n command: dict[str, CommandHandler] = field(default_factory=dict)\n block_actions: dict[str, BlockActionHandler] = field(default_factory=dict)\n modal: dict[str, ModalHandler] = field(default_factory=dict)\n modal_closed: dict[str, ModalHandler] = field(default_factory=dict)\n\n\n# Source: src/machine/utils/logging.py\ndef configure_logging(settings: Mapping[str, Any]) -> None:\n \"\"\"\n Configure logging with structlog. This function will configure structlog to use the right processors to add\n revelant metadata to the logs, such as timestamp, source file, line number, and function name.\n Next to that, it will configure all standard logging handlers to use structlog for formatting.\n :return: None\n \"\"\"\n\n # These processors are used both by the logs generated through structlog as well as the logs generated through\n # the stdlib logging module (incl. logs from third-party packages)\n shared_processors: list[Processor] = [\n structlog.contextvars.merge_contextvars,\n structlog.stdlib.add_logger_name,\n structlog.stdlib.add_log_level,\n structlog.stdlib.PositionalArgumentsFormatter(),\n structlog.processors.TimeStamper(fmt=\"iso\"),\n structlog.processors.StackInfoRenderer(),\n structlog.processors.format_exc_info,\n structlog.processors.UnicodeDecoder(),\n structlog.processors.CallsiteParameterAdder([\n CallsiteParameter.FILENAME,\n CallsiteParameter.FUNC_NAME,\n CallsiteParameter.LINENO,\n ]),\n ]\n # Configure structlog itself\n structlog.configure(\n processors=shared_processors + [structlog.stdlib.ProcessorFormatter.wrap_for_formatter],\n context_class=dict,\n wrapper_class=structlog.stdlib.BoundLogger,\n logger_factory=structlog.stdlib.LoggerFactory(),\n cache_logger_on_first_use=True,\n )\n # Create a formatter. Use Console renderer in terminal and JSON renderer when running in container\n renderer: Processor\n if sys.stdout.isatty(): # noqa: SIM108 (doesn't work with mypy)\n renderer = structlog.dev.ConsoleRenderer()\n else:\n renderer = structlog.processors.JSONRenderer()\n\n formatter = structlog.stdlib.ProcessorFormatter(\n foreign_pre_chain=shared_processors,\n processors=[\n structlog.stdlib.ProcessorFormatter.remove_processors_meta,\n renderer,\n ],\n )\n # All logging is going to be rendered by the stdlib logging module\n handler = logging.StreamHandler()\n # Use OUR `ProcessorFormatter` to format all `logging` entries.\n handler.setFormatter(formatter)\n root_logger = logging.getLogger()\n # We want to get rid of their pre-configured log handlers\n for h in root_logger.handlers:\n root_logger.removeHandler(h)\n root_logger.addHandler(handler)\n level_str = settings.get(\"LOGLEVEL\", \"ERROR\")\n # Get level as int so we can compare it\n level = logging.getLevelName(level_str)\n root_logger.setLevel(level)\n if level < logging.INFO:\n logging.getLogger(\"slack_sdk.socket_mode.aiohttp\").setLevel(logging.INFO)\n logging.getLogger(\"slack_sdk.web.async_base_client\").setLevel(logging.INFO)", "n_imports_parsed": 8, "n_files_resolved": 6, "n_chars_extracted": 20224}, "tests/test_plugin_registration.py::122": {"resolved_imports": ["src/machine/core.py", "src/machine/clients/slack.py", "src/machine/models/core.py", "src/machine/plugins/decorators.py", "src/machine/utils/collections.py", "src/machine/utils/logging.py"], "used_names": ["BlockActionHandler", "CommandHandler", "Machine", "MessageHandler", "ModalHandler", "RegisteredActions", "configure_logging", "pytest", "re"], "enclosing_function": "test_load_and_register_plugins", "extracted_code": "# Source: src/machine/core.py\nclass Machine:\n _socket_mode_client: SocketModeClient\n _client: SlackClient | None\n _storage_backend: MachineBaseStorage\n _settings: CaseInsensitiveDict | None\n _help: Manual\n _registered_actions: RegisteredActions\n _tz: ZoneInfo\n _scheduler: AsyncIOScheduler\n\n def __init__(self, settings: CaseInsensitiveDict | None = None):\n if settings is not None:\n self._settings = settings\n else:\n self._settings = None\n self._help = Manual(human={}, robot={})\n self._registered_actions = RegisteredActions()\n self._client = None\n\n async def _setup(self) -> None:\n logger.info(\"Initializing Slack Machine...\")\n\n found_local_settings = self._load_settings()\n assert self._settings is not None\n configure_logging(self._settings)\n if not found_local_settings:\n logger.warning(\"No local_settings found! Are you sure this is what you want?\")\n else:\n logger.debug(\"Found local settings %s\", self._settings)\n\n # Check if Slack token are present\n if \"SLACK_APP_TOKEN\" not in self._settings:\n logger.error(\"No SLACK_APP_TOKEN found in settings! I need that to work...\")\n sys.exit(1)\n if \"SLACK_BOT_TOKEN\" not in self._settings:\n logger.error(\"No SLACK_BOT_TOKEN found in settings! I need that to work...\")\n sys.exit(1)\n\n # Setup storage\n await self._setup_storage()\n\n # Setup Slack clients\n await self._setup_slack_clients()\n\n # Setup scheduling\n self._scheduler = AsyncIOScheduler(timezone=self._tz)\n\n # Load plugins\n await self._load_plugins()\n logger.debug(\"Registered plugin actions: %s\", self._registered_actions)\n logger.debug(\"Plugin help: %s\", self._help)\n\n def _load_settings(self) -> bool:\n logger.info(\"Loading settings...\")\n if self._settings is not None:\n found_local_settings = True\n else:\n settings_module = os.environ.get(\"SM_SETTINGS_MODULE\", \"local_settings\")\n self._settings, found_local_settings = import_settings(settings_module=settings_module)\n self._tz = ZoneInfo(self._settings[\"TZ\"])\n logger.info(\"Settings loaded!\")\n return found_local_settings\n\n async def _setup_storage(self) -> None:\n assert self._settings is not None\n storage_backend = self._settings.get(\"STORAGE_BACKEND\", \"machine.storage.backends.memory.MemoryStorage\")\n logger.info(\"Initializing storage backend %s...\", storage_backend)\n _, cls = import_string(storage_backend)[0]\n self._storage_backend = cls(self._settings)\n await self._storage_backend.init()\n logger.info(\"Storage backend %s initialized!\", storage_backend)\n\n async def _setup_slack_clients(self) -> None:\n assert self._settings is not None\n # Setup Slack socket mode client\n self._socket_mode_client = SocketModeClient(\n app_token=self._settings[\"SLACK_APP_TOKEN\"],\n web_client=AsyncWebClient(token=self._settings[\"SLACK_BOT_TOKEN\"]),\n proxy=self._settings[\"HTTP_PROXY\"],\n )\n\n # Setup high-level Slack client for plugins\n self._client = SlackClient(self._socket_mode_client, self._tz)\n await self._client.setup()\n\n # TODO: factor out plugin registration in separate class / set of functions\n async def _load_plugins(self) -> None:\n assert self._settings is not None\n if self._client is None:\n logger.error(\"Slack client not initialized!\")\n sys.exit(1)\n logger.debug(\"PLUGINS: %s\", self._settings[\"PLUGINS\"])\n for plugin in self._settings[\"PLUGINS\"]:\n for class_name, cls in import_string(plugin):\n if issubclass(cls, MachineBasePlugin) and cls is not MachineBasePlugin:\n logger.debug(\"Found a Machine plugin: %s\", plugin)\n storage = PluginStorage(class_name, self._storage_backend)\n instance = cls(self._client, self._settings, storage)\n missing_settings = self._register_plugin(class_name, instance)\n if missing_settings:\n logger.warning(\"Error loading plugin %s\", class_name)\n error_msg = f\"The following settings are missing: {', '.join(missing_settings)}\"\n logger.warning(error_msg)\n del instance\n else:\n await instance.init()\n logger.info(\"Plugin %s loaded\", class_name)\n await self._storage_backend.set(\"manual\", dill.dumps(self._help))\n\n def _register_plugin(self, plugin_class_name: str, cls_instance: MachineBasePlugin) -> list[str] | None:\n missing_settings = []\n cls_instance_for_missing_settings = cast(DecoratedPluginFunc, cls_instance)\n missing_settings.extend(self._check_missing_settings(cls_instance_for_missing_settings))\n methods = inspect.getmembers(cls_instance, predicate=inspect.ismethod)\n for _, fn in methods:\n method_for_missing_settings = cast(DecoratedPluginFunc, fn)\n missing_settings.extend(self._check_missing_settings(method_for_missing_settings))\n if missing_settings:\n return missing_settings\n\n class_help = cls_instance.__doc__.splitlines()[0] if cls_instance.__doc__ else plugin_class_name\n self._help.human[class_help] = self._help.human.get(class_help, {})\n self._help.robot[class_help] = self._help.robot.get(class_help, [])\n for name, fn in methods:\n if hasattr(fn, \"metadata\"):\n self._register_plugin_actions(plugin_class_name, fn.metadata, cls_instance, name, fn, class_help)\n return None\n\n def _check_missing_settings(self, fn_or_class: DecoratedPluginFunc) -> list[str]:\n missing_settings = []\n if hasattr(fn_or_class, \"metadata\") and isinstance(fn_or_class.metadata, Metadata):\n for setting in fn_or_class.metadata.required_settings:\n if self._settings is None or setting not in self._settings:\n missing_settings.append(setting.upper())\n return missing_settings\n\n def _register_plugin_actions(\n self,\n plugin_class_name: str,\n metadata: Metadata,\n cls_instance: MachineBasePlugin,\n fn_name: str,\n fn: Callable[..., Awaitable[None]],\n class_help: str,\n ) -> None:\n fq_fn_name = f\"{plugin_class_name}.{fn_name}\"\n if fn.__doc__:\n self._help.human[class_help][fq_fn_name] = self._parse_human_help(fn.__doc__)\n for matcher_config in metadata.plugin_actions.listen_to:\n self._register_message_handler(\n type_=\"listen_to\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n matcher_config=matcher_config,\n class_help=class_help,\n )\n for matcher_config in metadata.plugin_actions.respond_to:\n self._register_message_handler(\n type_=\"respond_to\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n matcher_config=matcher_config,\n class_help=class_help,\n )\n for event in metadata.plugin_actions.process:\n self._registered_actions.process[event] = self._registered_actions.process.get(event, {})\n key = f\"{fq_fn_name}-{event}\"\n self._registered_actions.process[event][key] = fn\n for command_config in metadata.plugin_actions.commands:\n self._register_command_handler(\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n command_config=command_config,\n class_help=class_help,\n )\n for block_action_config in metadata.plugin_actions.actions:\n self._register_block_action_handler(\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n block_action_config=block_action_config,\n class_help=class_help,\n )\n for modal_config in metadata.plugin_actions.modal_submissions:\n self._register_modal_handler(\n type_=\"modal\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n modal_config=modal_config,\n class_help=class_help,\n )\n for modal_config in metadata.plugin_actions.modal_closures:\n self._register_modal_handler(\n type_=\"modal_closed\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n modal_config=modal_config,\n class_help=class_help,\n )\n\n if metadata.plugin_actions.schedule is not None:\n self._scheduler.add_job(\n fn,\n trigger=\"cron\",\n args=[],\n id=fq_fn_name,\n replace_existing=True,\n **metadata.plugin_actions.schedule,\n )\n\n def _register_message_handler(\n self,\n type_: Literal[\"listen_to\", \"respond_to\"],\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n matcher_config: MatcherConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n handler = MessageHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n regex=matcher_config.regex,\n handle_message_changed=matcher_config.handle_changed_message,\n )\n key = f\"{fq_fn_name}-{matcher_config.regex.pattern}\"\n getattr(self._registered_actions, type_)[key] = handler\n self._help.robot[class_help].append(self._parse_robot_help(matcher_config, type_))\n\n def _register_command_handler(\n self,\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n command_config: CommandConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n logger.debug(\"signature of command handler\", signature=signature, function=fq_fn_name)\n handler = CommandHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n command=command_config.command,\n is_generator=command_config.is_generator,\n )\n command = command_config.command\n if command in self._registered_actions.command:\n logger.warning(\"command was already defined, previous handler will be overwritten!\", command=command)\n self._registered_actions.command[command] = handler\n # TODO: add to help\n\n def _register_block_action_handler(\n self,\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n block_action_config: ActionConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n logger.debug(\"signature of block action handler\", signature=signature, function=fq_fn_name)\n handler = BlockActionHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n action_id_matcher=block_action_config.action_id,\n block_id_matcher=block_action_config.block_id,\n )\n action_id = matcher_to_str(block_action_config.action_id)\n block_id = matcher_to_str(block_action_config.block_id)\n key = f\"{fq_fn_name}-{action_id}-{block_id}\"\n self._registered_actions.block_actions[key] = handler\n\n def _register_modal_handler(\n self,\n type_: Literal[\"modal\", \"modal_closed\"],\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n modal_config: ModalConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n logger.debug(\"signature of modal handler\", signature=signature, function=fq_fn_name)\n handler = ModalHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n callback_id_matcher=modal_config.callback_id,\n is_generator=modal_config.is_generator,\n )\n key = f\"{fq_fn_name}-{matcher_to_str(modal_config.callback_id)}\"\n getattr(self._registered_actions, type_)[key] = handler\n\n @staticmethod\n def _parse_human_help(doc: str) -> HumanHelp:\n summary = doc.splitlines()[0].split(\":\")\n if len(summary) > 1:\n command = summary[0].strip()\n cmd_help = summary[1].strip()\n else:\n command = \"??\"\n cmd_help = summary[0].strip()\n return HumanHelp(command=command, help=cmd_help)\n\n @staticmethod\n def _parse_robot_help(matcher_config: MatcherConfig, action: str) -> str:\n handle_message_changed_suffix = \" [includes changed messages]\" if matcher_config.handle_changed_message else \"\"\n if action == \"respond_to\":\n return f\"@botname {matcher_config.regex.pattern}{handle_message_changed_suffix}\"\n else:\n return f\"{matcher_config.regex.pattern}{handle_message_changed_suffix}\"\n\n async def run(self) -> None:\n await self._setup()\n assert self._settings is not None\n if self._client is None:\n logger.error(\"Slack client not initialized!\")\n sys.exit(1)\n\n bot_id = self._client.bot_info[\"user_id\"]\n bot_name = self._client.bot_info[\"name\"]\n\n if self._settings.get(\"LOGLEVEL\", \"ERROR\").upper() == \"DEBUG\":\n self._client.register_handler(log_request)\n\n message_handler = create_message_handler(\n self._registered_actions, self._settings, bot_id, bot_name, self._client\n )\n generic_event_handler = create_generic_event_handler(self._registered_actions)\n slash_command_handler = create_slash_command_handler(self._registered_actions, self._client)\n block_action_handler = create_interactive_handler(self._registered_actions, self._client)\n\n self._client.register_handler(message_handler)\n self._client.register_handler(generic_event_handler)\n self._client.register_handler(slash_command_handler)\n self._client.register_handler(block_action_handler)\n # Establish a WebSocket connection to the Socket Mode servers\n await self._socket_mode_client.connect()\n logger.info(\"Connected to Slack\")\n\n self._scheduler.start()\n logger.info(\"Scheduler started\")\n\n # Just not to stop this process\n await asyncio.sleep(float(\"inf\"))\n\n async def close(self) -> None:\n closables = [self._socket_mode_client.close(), self._storage_backend.close()]\n await asyncio.gather(*closables)\n\n\n# Source: src/machine/models/core.py\nclass MessageHandler:\n class_: MachineBasePlugin\n class_name: str\n function: Callable[..., Awaitable[None]]\n function_signature: Signature\n regex: re.Pattern[str]\n handle_message_changed: bool\n\nclass CommandHandler:\n class_: MachineBasePlugin\n class_name: str\n function: Callable[..., Awaitable[None] | AsyncGenerator[dict | JsonObject | str, None]]\n function_signature: Signature\n command: str\n is_generator: bool\n\nclass BlockActionHandler:\n class_: MachineBasePlugin\n class_name: str\n function: Callable[..., Awaitable[None]]\n function_signature: Signature\n action_id_matcher: Union[re.Pattern[str], str, None]\n block_id_matcher: Union[re.Pattern[str], str, None]\n\nclass ModalHandler:\n class_: MachineBasePlugin\n class_name: str\n function: Callable[..., Awaitable[None]]\n function_signature: Signature\n callback_id_matcher: Union[re.Pattern[str], str]\n is_generator: bool\n\nclass RegisteredActions:\n listen_to: dict[str, MessageHandler] = field(default_factory=dict)\n respond_to: dict[str, MessageHandler] = field(default_factory=dict)\n process: dict[str, dict[str, Callable[[dict[str, Any]], Awaitable[None]]]] = field(default_factory=dict)\n command: dict[str, CommandHandler] = field(default_factory=dict)\n block_actions: dict[str, BlockActionHandler] = field(default_factory=dict)\n modal: dict[str, ModalHandler] = field(default_factory=dict)\n modal_closed: dict[str, ModalHandler] = field(default_factory=dict)\n\n\n# Source: src/machine/utils/logging.py\ndef configure_logging(settings: Mapping[str, Any]) -> None:\n \"\"\"\n Configure logging with structlog. This function will configure structlog to use the right processors to add\n revelant metadata to the logs, such as timestamp, source file, line number, and function name.\n Next to that, it will configure all standard logging handlers to use structlog for formatting.\n :return: None\n \"\"\"\n\n # These processors are used both by the logs generated through structlog as well as the logs generated through\n # the stdlib logging module (incl. logs from third-party packages)\n shared_processors: list[Processor] = [\n structlog.contextvars.merge_contextvars,\n structlog.stdlib.add_logger_name,\n structlog.stdlib.add_log_level,\n structlog.stdlib.PositionalArgumentsFormatter(),\n structlog.processors.TimeStamper(fmt=\"iso\"),\n structlog.processors.StackInfoRenderer(),\n structlog.processors.format_exc_info,\n structlog.processors.UnicodeDecoder(),\n structlog.processors.CallsiteParameterAdder([\n CallsiteParameter.FILENAME,\n CallsiteParameter.FUNC_NAME,\n CallsiteParameter.LINENO,\n ]),\n ]\n # Configure structlog itself\n structlog.configure(\n processors=shared_processors + [structlog.stdlib.ProcessorFormatter.wrap_for_formatter],\n context_class=dict,\n wrapper_class=structlog.stdlib.BoundLogger,\n logger_factory=structlog.stdlib.LoggerFactory(),\n cache_logger_on_first_use=True,\n )\n # Create a formatter. Use Console renderer in terminal and JSON renderer when running in container\n renderer: Processor\n if sys.stdout.isatty(): # noqa: SIM108 (doesn't work with mypy)\n renderer = structlog.dev.ConsoleRenderer()\n else:\n renderer = structlog.processors.JSONRenderer()\n\n formatter = structlog.stdlib.ProcessorFormatter(\n foreign_pre_chain=shared_processors,\n processors=[\n structlog.stdlib.ProcessorFormatter.remove_processors_meta,\n renderer,\n ],\n )\n # All logging is going to be rendered by the stdlib logging module\n handler = logging.StreamHandler()\n # Use OUR `ProcessorFormatter` to format all `logging` entries.\n handler.setFormatter(formatter)\n root_logger = logging.getLogger()\n # We want to get rid of their pre-configured log handlers\n for h in root_logger.handlers:\n root_logger.removeHandler(h)\n root_logger.addHandler(handler)\n level_str = settings.get(\"LOGLEVEL\", \"ERROR\")\n # Get level as int so we can compare it\n level = logging.getLevelName(level_str)\n root_logger.setLevel(level)\n if level < logging.INFO:\n logging.getLogger(\"slack_sdk.socket_mode.aiohttp\").setLevel(logging.INFO)\n logging.getLogger(\"slack_sdk.web.async_base_client\").setLevel(logging.INFO)", "n_imports_parsed": 8, "n_files_resolved": 6, "n_chars_extracted": 20224}, "tests/test_plugin_registration.py::102": {"resolved_imports": ["src/machine/core.py", "src/machine/clients/slack.py", "src/machine/models/core.py", "src/machine/plugins/decorators.py", "src/machine/utils/collections.py", "src/machine/utils/logging.py"], "used_names": ["BlockActionHandler", "CommandHandler", "Machine", "MessageHandler", "ModalHandler", "RegisteredActions", "configure_logging", "pytest", "re"], "enclosing_function": "test_load_and_register_plugins", "extracted_code": "# Source: src/machine/core.py\nclass Machine:\n _socket_mode_client: SocketModeClient\n _client: SlackClient | None\n _storage_backend: MachineBaseStorage\n _settings: CaseInsensitiveDict | None\n _help: Manual\n _registered_actions: RegisteredActions\n _tz: ZoneInfo\n _scheduler: AsyncIOScheduler\n\n def __init__(self, settings: CaseInsensitiveDict | None = None):\n if settings is not None:\n self._settings = settings\n else:\n self._settings = None\n self._help = Manual(human={}, robot={})\n self._registered_actions = RegisteredActions()\n self._client = None\n\n async def _setup(self) -> None:\n logger.info(\"Initializing Slack Machine...\")\n\n found_local_settings = self._load_settings()\n assert self._settings is not None\n configure_logging(self._settings)\n if not found_local_settings:\n logger.warning(\"No local_settings found! Are you sure this is what you want?\")\n else:\n logger.debug(\"Found local settings %s\", self._settings)\n\n # Check if Slack token are present\n if \"SLACK_APP_TOKEN\" not in self._settings:\n logger.error(\"No SLACK_APP_TOKEN found in settings! I need that to work...\")\n sys.exit(1)\n if \"SLACK_BOT_TOKEN\" not in self._settings:\n logger.error(\"No SLACK_BOT_TOKEN found in settings! I need that to work...\")\n sys.exit(1)\n\n # Setup storage\n await self._setup_storage()\n\n # Setup Slack clients\n await self._setup_slack_clients()\n\n # Setup scheduling\n self._scheduler = AsyncIOScheduler(timezone=self._tz)\n\n # Load plugins\n await self._load_plugins()\n logger.debug(\"Registered plugin actions: %s\", self._registered_actions)\n logger.debug(\"Plugin help: %s\", self._help)\n\n def _load_settings(self) -> bool:\n logger.info(\"Loading settings...\")\n if self._settings is not None:\n found_local_settings = True\n else:\n settings_module = os.environ.get(\"SM_SETTINGS_MODULE\", \"local_settings\")\n self._settings, found_local_settings = import_settings(settings_module=settings_module)\n self._tz = ZoneInfo(self._settings[\"TZ\"])\n logger.info(\"Settings loaded!\")\n return found_local_settings\n\n async def _setup_storage(self) -> None:\n assert self._settings is not None\n storage_backend = self._settings.get(\"STORAGE_BACKEND\", \"machine.storage.backends.memory.MemoryStorage\")\n logger.info(\"Initializing storage backend %s...\", storage_backend)\n _, cls = import_string(storage_backend)[0]\n self._storage_backend = cls(self._settings)\n await self._storage_backend.init()\n logger.info(\"Storage backend %s initialized!\", storage_backend)\n\n async def _setup_slack_clients(self) -> None:\n assert self._settings is not None\n # Setup Slack socket mode client\n self._socket_mode_client = SocketModeClient(\n app_token=self._settings[\"SLACK_APP_TOKEN\"],\n web_client=AsyncWebClient(token=self._settings[\"SLACK_BOT_TOKEN\"]),\n proxy=self._settings[\"HTTP_PROXY\"],\n )\n\n # Setup high-level Slack client for plugins\n self._client = SlackClient(self._socket_mode_client, self._tz)\n await self._client.setup()\n\n # TODO: factor out plugin registration in separate class / set of functions\n async def _load_plugins(self) -> None:\n assert self._settings is not None\n if self._client is None:\n logger.error(\"Slack client not initialized!\")\n sys.exit(1)\n logger.debug(\"PLUGINS: %s\", self._settings[\"PLUGINS\"])\n for plugin in self._settings[\"PLUGINS\"]:\n for class_name, cls in import_string(plugin):\n if issubclass(cls, MachineBasePlugin) and cls is not MachineBasePlugin:\n logger.debug(\"Found a Machine plugin: %s\", plugin)\n storage = PluginStorage(class_name, self._storage_backend)\n instance = cls(self._client, self._settings, storage)\n missing_settings = self._register_plugin(class_name, instance)\n if missing_settings:\n logger.warning(\"Error loading plugin %s\", class_name)\n error_msg = f\"The following settings are missing: {', '.join(missing_settings)}\"\n logger.warning(error_msg)\n del instance\n else:\n await instance.init()\n logger.info(\"Plugin %s loaded\", class_name)\n await self._storage_backend.set(\"manual\", dill.dumps(self._help))\n\n def _register_plugin(self, plugin_class_name: str, cls_instance: MachineBasePlugin) -> list[str] | None:\n missing_settings = []\n cls_instance_for_missing_settings = cast(DecoratedPluginFunc, cls_instance)\n missing_settings.extend(self._check_missing_settings(cls_instance_for_missing_settings))\n methods = inspect.getmembers(cls_instance, predicate=inspect.ismethod)\n for _, fn in methods:\n method_for_missing_settings = cast(DecoratedPluginFunc, fn)\n missing_settings.extend(self._check_missing_settings(method_for_missing_settings))\n if missing_settings:\n return missing_settings\n\n class_help = cls_instance.__doc__.splitlines()[0] if cls_instance.__doc__ else plugin_class_name\n self._help.human[class_help] = self._help.human.get(class_help, {})\n self._help.robot[class_help] = self._help.robot.get(class_help, [])\n for name, fn in methods:\n if hasattr(fn, \"metadata\"):\n self._register_plugin_actions(plugin_class_name, fn.metadata, cls_instance, name, fn, class_help)\n return None\n\n def _check_missing_settings(self, fn_or_class: DecoratedPluginFunc) -> list[str]:\n missing_settings = []\n if hasattr(fn_or_class, \"metadata\") and isinstance(fn_or_class.metadata, Metadata):\n for setting in fn_or_class.metadata.required_settings:\n if self._settings is None or setting not in self._settings:\n missing_settings.append(setting.upper())\n return missing_settings\n\n def _register_plugin_actions(\n self,\n plugin_class_name: str,\n metadata: Metadata,\n cls_instance: MachineBasePlugin,\n fn_name: str,\n fn: Callable[..., Awaitable[None]],\n class_help: str,\n ) -> None:\n fq_fn_name = f\"{plugin_class_name}.{fn_name}\"\n if fn.__doc__:\n self._help.human[class_help][fq_fn_name] = self._parse_human_help(fn.__doc__)\n for matcher_config in metadata.plugin_actions.listen_to:\n self._register_message_handler(\n type_=\"listen_to\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n matcher_config=matcher_config,\n class_help=class_help,\n )\n for matcher_config in metadata.plugin_actions.respond_to:\n self._register_message_handler(\n type_=\"respond_to\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n matcher_config=matcher_config,\n class_help=class_help,\n )\n for event in metadata.plugin_actions.process:\n self._registered_actions.process[event] = self._registered_actions.process.get(event, {})\n key = f\"{fq_fn_name}-{event}\"\n self._registered_actions.process[event][key] = fn\n for command_config in metadata.plugin_actions.commands:\n self._register_command_handler(\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n command_config=command_config,\n class_help=class_help,\n )\n for block_action_config in metadata.plugin_actions.actions:\n self._register_block_action_handler(\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n block_action_config=block_action_config,\n class_help=class_help,\n )\n for modal_config in metadata.plugin_actions.modal_submissions:\n self._register_modal_handler(\n type_=\"modal\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n modal_config=modal_config,\n class_help=class_help,\n )\n for modal_config in metadata.plugin_actions.modal_closures:\n self._register_modal_handler(\n type_=\"modal_closed\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n modal_config=modal_config,\n class_help=class_help,\n )\n\n if metadata.plugin_actions.schedule is not None:\n self._scheduler.add_job(\n fn,\n trigger=\"cron\",\n args=[],\n id=fq_fn_name,\n replace_existing=True,\n **metadata.plugin_actions.schedule,\n )\n\n def _register_message_handler(\n self,\n type_: Literal[\"listen_to\", \"respond_to\"],\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n matcher_config: MatcherConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n handler = MessageHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n regex=matcher_config.regex,\n handle_message_changed=matcher_config.handle_changed_message,\n )\n key = f\"{fq_fn_name}-{matcher_config.regex.pattern}\"\n getattr(self._registered_actions, type_)[key] = handler\n self._help.robot[class_help].append(self._parse_robot_help(matcher_config, type_))\n\n def _register_command_handler(\n self,\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n command_config: CommandConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n logger.debug(\"signature of command handler\", signature=signature, function=fq_fn_name)\n handler = CommandHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n command=command_config.command,\n is_generator=command_config.is_generator,\n )\n command = command_config.command\n if command in self._registered_actions.command:\n logger.warning(\"command was already defined, previous handler will be overwritten!\", command=command)\n self._registered_actions.command[command] = handler\n # TODO: add to help\n\n def _register_block_action_handler(\n self,\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n block_action_config: ActionConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n logger.debug(\"signature of block action handler\", signature=signature, function=fq_fn_name)\n handler = BlockActionHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n action_id_matcher=block_action_config.action_id,\n block_id_matcher=block_action_config.block_id,\n )\n action_id = matcher_to_str(block_action_config.action_id)\n block_id = matcher_to_str(block_action_config.block_id)\n key = f\"{fq_fn_name}-{action_id}-{block_id}\"\n self._registered_actions.block_actions[key] = handler\n\n def _register_modal_handler(\n self,\n type_: Literal[\"modal\", \"modal_closed\"],\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n modal_config: ModalConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n logger.debug(\"signature of modal handler\", signature=signature, function=fq_fn_name)\n handler = ModalHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n callback_id_matcher=modal_config.callback_id,\n is_generator=modal_config.is_generator,\n )\n key = f\"{fq_fn_name}-{matcher_to_str(modal_config.callback_id)}\"\n getattr(self._registered_actions, type_)[key] = handler\n\n @staticmethod\n def _parse_human_help(doc: str) -> HumanHelp:\n summary = doc.splitlines()[0].split(\":\")\n if len(summary) > 1:\n command = summary[0].strip()\n cmd_help = summary[1].strip()\n else:\n command = \"??\"\n cmd_help = summary[0].strip()\n return HumanHelp(command=command, help=cmd_help)\n\n @staticmethod\n def _parse_robot_help(matcher_config: MatcherConfig, action: str) -> str:\n handle_message_changed_suffix = \" [includes changed messages]\" if matcher_config.handle_changed_message else \"\"\n if action == \"respond_to\":\n return f\"@botname {matcher_config.regex.pattern}{handle_message_changed_suffix}\"\n else:\n return f\"{matcher_config.regex.pattern}{handle_message_changed_suffix}\"\n\n async def run(self) -> None:\n await self._setup()\n assert self._settings is not None\n if self._client is None:\n logger.error(\"Slack client not initialized!\")\n sys.exit(1)\n\n bot_id = self._client.bot_info[\"user_id\"]\n bot_name = self._client.bot_info[\"name\"]\n\n if self._settings.get(\"LOGLEVEL\", \"ERROR\").upper() == \"DEBUG\":\n self._client.register_handler(log_request)\n\n message_handler = create_message_handler(\n self._registered_actions, self._settings, bot_id, bot_name, self._client\n )\n generic_event_handler = create_generic_event_handler(self._registered_actions)\n slash_command_handler = create_slash_command_handler(self._registered_actions, self._client)\n block_action_handler = create_interactive_handler(self._registered_actions, self._client)\n\n self._client.register_handler(message_handler)\n self._client.register_handler(generic_event_handler)\n self._client.register_handler(slash_command_handler)\n self._client.register_handler(block_action_handler)\n # Establish a WebSocket connection to the Socket Mode servers\n await self._socket_mode_client.connect()\n logger.info(\"Connected to Slack\")\n\n self._scheduler.start()\n logger.info(\"Scheduler started\")\n\n # Just not to stop this process\n await asyncio.sleep(float(\"inf\"))\n\n async def close(self) -> None:\n closables = [self._socket_mode_client.close(), self._storage_backend.close()]\n await asyncio.gather(*closables)\n\n\n# Source: src/machine/models/core.py\nclass MessageHandler:\n class_: MachineBasePlugin\n class_name: str\n function: Callable[..., Awaitable[None]]\n function_signature: Signature\n regex: re.Pattern[str]\n handle_message_changed: bool\n\nclass CommandHandler:\n class_: MachineBasePlugin\n class_name: str\n function: Callable[..., Awaitable[None] | AsyncGenerator[dict | JsonObject | str, None]]\n function_signature: Signature\n command: str\n is_generator: bool\n\nclass BlockActionHandler:\n class_: MachineBasePlugin\n class_name: str\n function: Callable[..., Awaitable[None]]\n function_signature: Signature\n action_id_matcher: Union[re.Pattern[str], str, None]\n block_id_matcher: Union[re.Pattern[str], str, None]\n\nclass ModalHandler:\n class_: MachineBasePlugin\n class_name: str\n function: Callable[..., Awaitable[None]]\n function_signature: Signature\n callback_id_matcher: Union[re.Pattern[str], str]\n is_generator: bool\n\nclass RegisteredActions:\n listen_to: dict[str, MessageHandler] = field(default_factory=dict)\n respond_to: dict[str, MessageHandler] = field(default_factory=dict)\n process: dict[str, dict[str, Callable[[dict[str, Any]], Awaitable[None]]]] = field(default_factory=dict)\n command: dict[str, CommandHandler] = field(default_factory=dict)\n block_actions: dict[str, BlockActionHandler] = field(default_factory=dict)\n modal: dict[str, ModalHandler] = field(default_factory=dict)\n modal_closed: dict[str, ModalHandler] = field(default_factory=dict)\n\n\n# Source: src/machine/utils/logging.py\ndef configure_logging(settings: Mapping[str, Any]) -> None:\n \"\"\"\n Configure logging with structlog. This function will configure structlog to use the right processors to add\n revelant metadata to the logs, such as timestamp, source file, line number, and function name.\n Next to that, it will configure all standard logging handlers to use structlog for formatting.\n :return: None\n \"\"\"\n\n # These processors are used both by the logs generated through structlog as well as the logs generated through\n # the stdlib logging module (incl. logs from third-party packages)\n shared_processors: list[Processor] = [\n structlog.contextvars.merge_contextvars,\n structlog.stdlib.add_logger_name,\n structlog.stdlib.add_log_level,\n structlog.stdlib.PositionalArgumentsFormatter(),\n structlog.processors.TimeStamper(fmt=\"iso\"),\n structlog.processors.StackInfoRenderer(),\n structlog.processors.format_exc_info,\n structlog.processors.UnicodeDecoder(),\n structlog.processors.CallsiteParameterAdder([\n CallsiteParameter.FILENAME,\n CallsiteParameter.FUNC_NAME,\n CallsiteParameter.LINENO,\n ]),\n ]\n # Configure structlog itself\n structlog.configure(\n processors=shared_processors + [structlog.stdlib.ProcessorFormatter.wrap_for_formatter],\n context_class=dict,\n wrapper_class=structlog.stdlib.BoundLogger,\n logger_factory=structlog.stdlib.LoggerFactory(),\n cache_logger_on_first_use=True,\n )\n # Create a formatter. Use Console renderer in terminal and JSON renderer when running in container\n renderer: Processor\n if sys.stdout.isatty(): # noqa: SIM108 (doesn't work with mypy)\n renderer = structlog.dev.ConsoleRenderer()\n else:\n renderer = structlog.processors.JSONRenderer()\n\n formatter = structlog.stdlib.ProcessorFormatter(\n foreign_pre_chain=shared_processors,\n processors=[\n structlog.stdlib.ProcessorFormatter.remove_processors_meta,\n renderer,\n ],\n )\n # All logging is going to be rendered by the stdlib logging module\n handler = logging.StreamHandler()\n # Use OUR `ProcessorFormatter` to format all `logging` entries.\n handler.setFormatter(formatter)\n root_logger = logging.getLogger()\n # We want to get rid of their pre-configured log handlers\n for h in root_logger.handlers:\n root_logger.removeHandler(h)\n root_logger.addHandler(handler)\n level_str = settings.get(\"LOGLEVEL\", \"ERROR\")\n # Get level as int so we can compare it\n level = logging.getLevelName(level_str)\n root_logger.setLevel(level)\n if level < logging.INFO:\n logging.getLogger(\"slack_sdk.socket_mode.aiohttp\").setLevel(logging.INFO)\n logging.getLogger(\"slack_sdk.web.async_base_client\").setLevel(logging.INFO)", "n_imports_parsed": 8, "n_files_resolved": 6, "n_chars_extracted": 20224}, "tests/test_plugin_registration.py::135": {"resolved_imports": ["src/machine/core.py", "src/machine/clients/slack.py", "src/machine/models/core.py", "src/machine/plugins/decorators.py", "src/machine/utils/collections.py", "src/machine/utils/logging.py"], "used_names": ["Machine", "pytest"], "enclosing_function": "test_plugin_storage_fq_plugin_name", "extracted_code": "# Source: src/machine/core.py\nclass Machine:\n _socket_mode_client: SocketModeClient\n _client: SlackClient | None\n _storage_backend: MachineBaseStorage\n _settings: CaseInsensitiveDict | None\n _help: Manual\n _registered_actions: RegisteredActions\n _tz: ZoneInfo\n _scheduler: AsyncIOScheduler\n\n def __init__(self, settings: CaseInsensitiveDict | None = None):\n if settings is not None:\n self._settings = settings\n else:\n self._settings = None\n self._help = Manual(human={}, robot={})\n self._registered_actions = RegisteredActions()\n self._client = None\n\n async def _setup(self) -> None:\n logger.info(\"Initializing Slack Machine...\")\n\n found_local_settings = self._load_settings()\n assert self._settings is not None\n configure_logging(self._settings)\n if not found_local_settings:\n logger.warning(\"No local_settings found! Are you sure this is what you want?\")\n else:\n logger.debug(\"Found local settings %s\", self._settings)\n\n # Check if Slack token are present\n if \"SLACK_APP_TOKEN\" not in self._settings:\n logger.error(\"No SLACK_APP_TOKEN found in settings! I need that to work...\")\n sys.exit(1)\n if \"SLACK_BOT_TOKEN\" not in self._settings:\n logger.error(\"No SLACK_BOT_TOKEN found in settings! I need that to work...\")\n sys.exit(1)\n\n # Setup storage\n await self._setup_storage()\n\n # Setup Slack clients\n await self._setup_slack_clients()\n\n # Setup scheduling\n self._scheduler = AsyncIOScheduler(timezone=self._tz)\n\n # Load plugins\n await self._load_plugins()\n logger.debug(\"Registered plugin actions: %s\", self._registered_actions)\n logger.debug(\"Plugin help: %s\", self._help)\n\n def _load_settings(self) -> bool:\n logger.info(\"Loading settings...\")\n if self._settings is not None:\n found_local_settings = True\n else:\n settings_module = os.environ.get(\"SM_SETTINGS_MODULE\", \"local_settings\")\n self._settings, found_local_settings = import_settings(settings_module=settings_module)\n self._tz = ZoneInfo(self._settings[\"TZ\"])\n logger.info(\"Settings loaded!\")\n return found_local_settings\n\n async def _setup_storage(self) -> None:\n assert self._settings is not None\n storage_backend = self._settings.get(\"STORAGE_BACKEND\", \"machine.storage.backends.memory.MemoryStorage\")\n logger.info(\"Initializing storage backend %s...\", storage_backend)\n _, cls = import_string(storage_backend)[0]\n self._storage_backend = cls(self._settings)\n await self._storage_backend.init()\n logger.info(\"Storage backend %s initialized!\", storage_backend)\n\n async def _setup_slack_clients(self) -> None:\n assert self._settings is not None\n # Setup Slack socket mode client\n self._socket_mode_client = SocketModeClient(\n app_token=self._settings[\"SLACK_APP_TOKEN\"],\n web_client=AsyncWebClient(token=self._settings[\"SLACK_BOT_TOKEN\"]),\n proxy=self._settings[\"HTTP_PROXY\"],\n )\n\n # Setup high-level Slack client for plugins\n self._client = SlackClient(self._socket_mode_client, self._tz)\n await self._client.setup()\n\n # TODO: factor out plugin registration in separate class / set of functions\n async def _load_plugins(self) -> None:\n assert self._settings is not None\n if self._client is None:\n logger.error(\"Slack client not initialized!\")\n sys.exit(1)\n logger.debug(\"PLUGINS: %s\", self._settings[\"PLUGINS\"])\n for plugin in self._settings[\"PLUGINS\"]:\n for class_name, cls in import_string(plugin):\n if issubclass(cls, MachineBasePlugin) and cls is not MachineBasePlugin:\n logger.debug(\"Found a Machine plugin: %s\", plugin)\n storage = PluginStorage(class_name, self._storage_backend)\n instance = cls(self._client, self._settings, storage)\n missing_settings = self._register_plugin(class_name, instance)\n if missing_settings:\n logger.warning(\"Error loading plugin %s\", class_name)\n error_msg = f\"The following settings are missing: {', '.join(missing_settings)}\"\n logger.warning(error_msg)\n del instance\n else:\n await instance.init()\n logger.info(\"Plugin %s loaded\", class_name)\n await self._storage_backend.set(\"manual\", dill.dumps(self._help))\n\n def _register_plugin(self, plugin_class_name: str, cls_instance: MachineBasePlugin) -> list[str] | None:\n missing_settings = []\n cls_instance_for_missing_settings = cast(DecoratedPluginFunc, cls_instance)\n missing_settings.extend(self._check_missing_settings(cls_instance_for_missing_settings))\n methods = inspect.getmembers(cls_instance, predicate=inspect.ismethod)\n for _, fn in methods:\n method_for_missing_settings = cast(DecoratedPluginFunc, fn)\n missing_settings.extend(self._check_missing_settings(method_for_missing_settings))\n if missing_settings:\n return missing_settings\n\n class_help = cls_instance.__doc__.splitlines()[0] if cls_instance.__doc__ else plugin_class_name\n self._help.human[class_help] = self._help.human.get(class_help, {})\n self._help.robot[class_help] = self._help.robot.get(class_help, [])\n for name, fn in methods:\n if hasattr(fn, \"metadata\"):\n self._register_plugin_actions(plugin_class_name, fn.metadata, cls_instance, name, fn, class_help)\n return None\n\n def _check_missing_settings(self, fn_or_class: DecoratedPluginFunc) -> list[str]:\n missing_settings = []\n if hasattr(fn_or_class, \"metadata\") and isinstance(fn_or_class.metadata, Metadata):\n for setting in fn_or_class.metadata.required_settings:\n if self._settings is None or setting not in self._settings:\n missing_settings.append(setting.upper())\n return missing_settings\n\n def _register_plugin_actions(\n self,\n plugin_class_name: str,\n metadata: Metadata,\n cls_instance: MachineBasePlugin,\n fn_name: str,\n fn: Callable[..., Awaitable[None]],\n class_help: str,\n ) -> None:\n fq_fn_name = f\"{plugin_class_name}.{fn_name}\"\n if fn.__doc__:\n self._help.human[class_help][fq_fn_name] = self._parse_human_help(fn.__doc__)\n for matcher_config in metadata.plugin_actions.listen_to:\n self._register_message_handler(\n type_=\"listen_to\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n matcher_config=matcher_config,\n class_help=class_help,\n )\n for matcher_config in metadata.plugin_actions.respond_to:\n self._register_message_handler(\n type_=\"respond_to\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n matcher_config=matcher_config,\n class_help=class_help,\n )\n for event in metadata.plugin_actions.process:\n self._registered_actions.process[event] = self._registered_actions.process.get(event, {})\n key = f\"{fq_fn_name}-{event}\"\n self._registered_actions.process[event][key] = fn\n for command_config in metadata.plugin_actions.commands:\n self._register_command_handler(\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n command_config=command_config,\n class_help=class_help,\n )\n for block_action_config in metadata.plugin_actions.actions:\n self._register_block_action_handler(\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n block_action_config=block_action_config,\n class_help=class_help,\n )\n for modal_config in metadata.plugin_actions.modal_submissions:\n self._register_modal_handler(\n type_=\"modal\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n modal_config=modal_config,\n class_help=class_help,\n )\n for modal_config in metadata.plugin_actions.modal_closures:\n self._register_modal_handler(\n type_=\"modal_closed\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n modal_config=modal_config,\n class_help=class_help,\n )\n\n if metadata.plugin_actions.schedule is not None:\n self._scheduler.add_job(\n fn,\n trigger=\"cron\",\n args=[],\n id=fq_fn_name,\n replace_existing=True,\n **metadata.plugin_actions.schedule,\n )\n\n def _register_message_handler(\n self,\n type_: Literal[\"listen_to\", \"respond_to\"],\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n matcher_config: MatcherConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n handler = MessageHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n regex=matcher_config.regex,\n handle_message_changed=matcher_config.handle_changed_message,\n )\n key = f\"{fq_fn_name}-{matcher_config.regex.pattern}\"\n getattr(self._registered_actions, type_)[key] = handler\n self._help.robot[class_help].append(self._parse_robot_help(matcher_config, type_))\n\n def _register_command_handler(\n self,\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n command_config: CommandConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n logger.debug(\"signature of command handler\", signature=signature, function=fq_fn_name)\n handler = CommandHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n command=command_config.command,\n is_generator=command_config.is_generator,\n )\n command = command_config.command\n if command in self._registered_actions.command:\n logger.warning(\"command was already defined, previous handler will be overwritten!\", command=command)\n self._registered_actions.command[command] = handler\n # TODO: add to help\n\n def _register_block_action_handler(\n self,\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n block_action_config: ActionConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n logger.debug(\"signature of block action handler\", signature=signature, function=fq_fn_name)\n handler = BlockActionHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n action_id_matcher=block_action_config.action_id,\n block_id_matcher=block_action_config.block_id,\n )\n action_id = matcher_to_str(block_action_config.action_id)\n block_id = matcher_to_str(block_action_config.block_id)\n key = f\"{fq_fn_name}-{action_id}-{block_id}\"\n self._registered_actions.block_actions[key] = handler\n\n def _register_modal_handler(\n self,\n type_: Literal[\"modal\", \"modal_closed\"],\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n modal_config: ModalConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n logger.debug(\"signature of modal handler\", signature=signature, function=fq_fn_name)\n handler = ModalHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n callback_id_matcher=modal_config.callback_id,\n is_generator=modal_config.is_generator,\n )\n key = f\"{fq_fn_name}-{matcher_to_str(modal_config.callback_id)}\"\n getattr(self._registered_actions, type_)[key] = handler\n\n @staticmethod\n def _parse_human_help(doc: str) -> HumanHelp:\n summary = doc.splitlines()[0].split(\":\")\n if len(summary) > 1:\n command = summary[0].strip()\n cmd_help = summary[1].strip()\n else:\n command = \"??\"\n cmd_help = summary[0].strip()\n return HumanHelp(command=command, help=cmd_help)\n\n @staticmethod\n def _parse_robot_help(matcher_config: MatcherConfig, action: str) -> str:\n handle_message_changed_suffix = \" [includes changed messages]\" if matcher_config.handle_changed_message else \"\"\n if action == \"respond_to\":\n return f\"@botname {matcher_config.regex.pattern}{handle_message_changed_suffix}\"\n else:\n return f\"{matcher_config.regex.pattern}{handle_message_changed_suffix}\"\n\n async def run(self) -> None:\n await self._setup()\n assert self._settings is not None\n if self._client is None:\n logger.error(\"Slack client not initialized!\")\n sys.exit(1)\n\n bot_id = self._client.bot_info[\"user_id\"]\n bot_name = self._client.bot_info[\"name\"]\n\n if self._settings.get(\"LOGLEVEL\", \"ERROR\").upper() == \"DEBUG\":\n self._client.register_handler(log_request)\n\n message_handler = create_message_handler(\n self._registered_actions, self._settings, bot_id, bot_name, self._client\n )\n generic_event_handler = create_generic_event_handler(self._registered_actions)\n slash_command_handler = create_slash_command_handler(self._registered_actions, self._client)\n block_action_handler = create_interactive_handler(self._registered_actions, self._client)\n\n self._client.register_handler(message_handler)\n self._client.register_handler(generic_event_handler)\n self._client.register_handler(slash_command_handler)\n self._client.register_handler(block_action_handler)\n # Establish a WebSocket connection to the Socket Mode servers\n await self._socket_mode_client.connect()\n logger.info(\"Connected to Slack\")\n\n self._scheduler.start()\n logger.info(\"Scheduler started\")\n\n # Just not to stop this process\n await asyncio.sleep(float(\"inf\"))\n\n async def close(self) -> None:\n closables = [self._socket_mode_client.close(), self._storage_backend.close()]\n await asyncio.gather(*closables)", "n_imports_parsed": 8, "n_files_resolved": 6, "n_chars_extracted": 15759}, "tests/test_plugin_registration.py::136": {"resolved_imports": ["src/machine/core.py", "src/machine/clients/slack.py", "src/machine/models/core.py", "src/machine/plugins/decorators.py", "src/machine/utils/collections.py", "src/machine/utils/logging.py"], "used_names": ["Machine", "pytest"], "enclosing_function": "test_plugin_storage_fq_plugin_name", "extracted_code": "# Source: src/machine/core.py\nclass Machine:\n _socket_mode_client: SocketModeClient\n _client: SlackClient | None\n _storage_backend: MachineBaseStorage\n _settings: CaseInsensitiveDict | None\n _help: Manual\n _registered_actions: RegisteredActions\n _tz: ZoneInfo\n _scheduler: AsyncIOScheduler\n\n def __init__(self, settings: CaseInsensitiveDict | None = None):\n if settings is not None:\n self._settings = settings\n else:\n self._settings = None\n self._help = Manual(human={}, robot={})\n self._registered_actions = RegisteredActions()\n self._client = None\n\n async def _setup(self) -> None:\n logger.info(\"Initializing Slack Machine...\")\n\n found_local_settings = self._load_settings()\n assert self._settings is not None\n configure_logging(self._settings)\n if not found_local_settings:\n logger.warning(\"No local_settings found! Are you sure this is what you want?\")\n else:\n logger.debug(\"Found local settings %s\", self._settings)\n\n # Check if Slack token are present\n if \"SLACK_APP_TOKEN\" not in self._settings:\n logger.error(\"No SLACK_APP_TOKEN found in settings! I need that to work...\")\n sys.exit(1)\n if \"SLACK_BOT_TOKEN\" not in self._settings:\n logger.error(\"No SLACK_BOT_TOKEN found in settings! I need that to work...\")\n sys.exit(1)\n\n # Setup storage\n await self._setup_storage()\n\n # Setup Slack clients\n await self._setup_slack_clients()\n\n # Setup scheduling\n self._scheduler = AsyncIOScheduler(timezone=self._tz)\n\n # Load plugins\n await self._load_plugins()\n logger.debug(\"Registered plugin actions: %s\", self._registered_actions)\n logger.debug(\"Plugin help: %s\", self._help)\n\n def _load_settings(self) -> bool:\n logger.info(\"Loading settings...\")\n if self._settings is not None:\n found_local_settings = True\n else:\n settings_module = os.environ.get(\"SM_SETTINGS_MODULE\", \"local_settings\")\n self._settings, found_local_settings = import_settings(settings_module=settings_module)\n self._tz = ZoneInfo(self._settings[\"TZ\"])\n logger.info(\"Settings loaded!\")\n return found_local_settings\n\n async def _setup_storage(self) -> None:\n assert self._settings is not None\n storage_backend = self._settings.get(\"STORAGE_BACKEND\", \"machine.storage.backends.memory.MemoryStorage\")\n logger.info(\"Initializing storage backend %s...\", storage_backend)\n _, cls = import_string(storage_backend)[0]\n self._storage_backend = cls(self._settings)\n await self._storage_backend.init()\n logger.info(\"Storage backend %s initialized!\", storage_backend)\n\n async def _setup_slack_clients(self) -> None:\n assert self._settings is not None\n # Setup Slack socket mode client\n self._socket_mode_client = SocketModeClient(\n app_token=self._settings[\"SLACK_APP_TOKEN\"],\n web_client=AsyncWebClient(token=self._settings[\"SLACK_BOT_TOKEN\"]),\n proxy=self._settings[\"HTTP_PROXY\"],\n )\n\n # Setup high-level Slack client for plugins\n self._client = SlackClient(self._socket_mode_client, self._tz)\n await self._client.setup()\n\n # TODO: factor out plugin registration in separate class / set of functions\n async def _load_plugins(self) -> None:\n assert self._settings is not None\n if self._client is None:\n logger.error(\"Slack client not initialized!\")\n sys.exit(1)\n logger.debug(\"PLUGINS: %s\", self._settings[\"PLUGINS\"])\n for plugin in self._settings[\"PLUGINS\"]:\n for class_name, cls in import_string(plugin):\n if issubclass(cls, MachineBasePlugin) and cls is not MachineBasePlugin:\n logger.debug(\"Found a Machine plugin: %s\", plugin)\n storage = PluginStorage(class_name, self._storage_backend)\n instance = cls(self._client, self._settings, storage)\n missing_settings = self._register_plugin(class_name, instance)\n if missing_settings:\n logger.warning(\"Error loading plugin %s\", class_name)\n error_msg = f\"The following settings are missing: {', '.join(missing_settings)}\"\n logger.warning(error_msg)\n del instance\n else:\n await instance.init()\n logger.info(\"Plugin %s loaded\", class_name)\n await self._storage_backend.set(\"manual\", dill.dumps(self._help))\n\n def _register_plugin(self, plugin_class_name: str, cls_instance: MachineBasePlugin) -> list[str] | None:\n missing_settings = []\n cls_instance_for_missing_settings = cast(DecoratedPluginFunc, cls_instance)\n missing_settings.extend(self._check_missing_settings(cls_instance_for_missing_settings))\n methods = inspect.getmembers(cls_instance, predicate=inspect.ismethod)\n for _, fn in methods:\n method_for_missing_settings = cast(DecoratedPluginFunc, fn)\n missing_settings.extend(self._check_missing_settings(method_for_missing_settings))\n if missing_settings:\n return missing_settings\n\n class_help = cls_instance.__doc__.splitlines()[0] if cls_instance.__doc__ else plugin_class_name\n self._help.human[class_help] = self._help.human.get(class_help, {})\n self._help.robot[class_help] = self._help.robot.get(class_help, [])\n for name, fn in methods:\n if hasattr(fn, \"metadata\"):\n self._register_plugin_actions(plugin_class_name, fn.metadata, cls_instance, name, fn, class_help)\n return None\n\n def _check_missing_settings(self, fn_or_class: DecoratedPluginFunc) -> list[str]:\n missing_settings = []\n if hasattr(fn_or_class, \"metadata\") and isinstance(fn_or_class.metadata, Metadata):\n for setting in fn_or_class.metadata.required_settings:\n if self._settings is None or setting not in self._settings:\n missing_settings.append(setting.upper())\n return missing_settings\n\n def _register_plugin_actions(\n self,\n plugin_class_name: str,\n metadata: Metadata,\n cls_instance: MachineBasePlugin,\n fn_name: str,\n fn: Callable[..., Awaitable[None]],\n class_help: str,\n ) -> None:\n fq_fn_name = f\"{plugin_class_name}.{fn_name}\"\n if fn.__doc__:\n self._help.human[class_help][fq_fn_name] = self._parse_human_help(fn.__doc__)\n for matcher_config in metadata.plugin_actions.listen_to:\n self._register_message_handler(\n type_=\"listen_to\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n matcher_config=matcher_config,\n class_help=class_help,\n )\n for matcher_config in metadata.plugin_actions.respond_to:\n self._register_message_handler(\n type_=\"respond_to\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n matcher_config=matcher_config,\n class_help=class_help,\n )\n for event in metadata.plugin_actions.process:\n self._registered_actions.process[event] = self._registered_actions.process.get(event, {})\n key = f\"{fq_fn_name}-{event}\"\n self._registered_actions.process[event][key] = fn\n for command_config in metadata.plugin_actions.commands:\n self._register_command_handler(\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n command_config=command_config,\n class_help=class_help,\n )\n for block_action_config in metadata.plugin_actions.actions:\n self._register_block_action_handler(\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n block_action_config=block_action_config,\n class_help=class_help,\n )\n for modal_config in metadata.plugin_actions.modal_submissions:\n self._register_modal_handler(\n type_=\"modal\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n modal_config=modal_config,\n class_help=class_help,\n )\n for modal_config in metadata.plugin_actions.modal_closures:\n self._register_modal_handler(\n type_=\"modal_closed\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n modal_config=modal_config,\n class_help=class_help,\n )\n\n if metadata.plugin_actions.schedule is not None:\n self._scheduler.add_job(\n fn,\n trigger=\"cron\",\n args=[],\n id=fq_fn_name,\n replace_existing=True,\n **metadata.plugin_actions.schedule,\n )\n\n def _register_message_handler(\n self,\n type_: Literal[\"listen_to\", \"respond_to\"],\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n matcher_config: MatcherConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n handler = MessageHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n regex=matcher_config.regex,\n handle_message_changed=matcher_config.handle_changed_message,\n )\n key = f\"{fq_fn_name}-{matcher_config.regex.pattern}\"\n getattr(self._registered_actions, type_)[key] = handler\n self._help.robot[class_help].append(self._parse_robot_help(matcher_config, type_))\n\n def _register_command_handler(\n self,\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n command_config: CommandConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n logger.debug(\"signature of command handler\", signature=signature, function=fq_fn_name)\n handler = CommandHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n command=command_config.command,\n is_generator=command_config.is_generator,\n )\n command = command_config.command\n if command in self._registered_actions.command:\n logger.warning(\"command was already defined, previous handler will be overwritten!\", command=command)\n self._registered_actions.command[command] = handler\n # TODO: add to help\n\n def _register_block_action_handler(\n self,\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n block_action_config: ActionConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n logger.debug(\"signature of block action handler\", signature=signature, function=fq_fn_name)\n handler = BlockActionHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n action_id_matcher=block_action_config.action_id,\n block_id_matcher=block_action_config.block_id,\n )\n action_id = matcher_to_str(block_action_config.action_id)\n block_id = matcher_to_str(block_action_config.block_id)\n key = f\"{fq_fn_name}-{action_id}-{block_id}\"\n self._registered_actions.block_actions[key] = handler\n\n def _register_modal_handler(\n self,\n type_: Literal[\"modal\", \"modal_closed\"],\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n modal_config: ModalConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n logger.debug(\"signature of modal handler\", signature=signature, function=fq_fn_name)\n handler = ModalHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n callback_id_matcher=modal_config.callback_id,\n is_generator=modal_config.is_generator,\n )\n key = f\"{fq_fn_name}-{matcher_to_str(modal_config.callback_id)}\"\n getattr(self._registered_actions, type_)[key] = handler\n\n @staticmethod\n def _parse_human_help(doc: str) -> HumanHelp:\n summary = doc.splitlines()[0].split(\":\")\n if len(summary) > 1:\n command = summary[0].strip()\n cmd_help = summary[1].strip()\n else:\n command = \"??\"\n cmd_help = summary[0].strip()\n return HumanHelp(command=command, help=cmd_help)\n\n @staticmethod\n def _parse_robot_help(matcher_config: MatcherConfig, action: str) -> str:\n handle_message_changed_suffix = \" [includes changed messages]\" if matcher_config.handle_changed_message else \"\"\n if action == \"respond_to\":\n return f\"@botname {matcher_config.regex.pattern}{handle_message_changed_suffix}\"\n else:\n return f\"{matcher_config.regex.pattern}{handle_message_changed_suffix}\"\n\n async def run(self) -> None:\n await self._setup()\n assert self._settings is not None\n if self._client is None:\n logger.error(\"Slack client not initialized!\")\n sys.exit(1)\n\n bot_id = self._client.bot_info[\"user_id\"]\n bot_name = self._client.bot_info[\"name\"]\n\n if self._settings.get(\"LOGLEVEL\", \"ERROR\").upper() == \"DEBUG\":\n self._client.register_handler(log_request)\n\n message_handler = create_message_handler(\n self._registered_actions, self._settings, bot_id, bot_name, self._client\n )\n generic_event_handler = create_generic_event_handler(self._registered_actions)\n slash_command_handler = create_slash_command_handler(self._registered_actions, self._client)\n block_action_handler = create_interactive_handler(self._registered_actions, self._client)\n\n self._client.register_handler(message_handler)\n self._client.register_handler(generic_event_handler)\n self._client.register_handler(slash_command_handler)\n self._client.register_handler(block_action_handler)\n # Establish a WebSocket connection to the Socket Mode servers\n await self._socket_mode_client.connect()\n logger.info(\"Connected to Slack\")\n\n self._scheduler.start()\n logger.info(\"Scheduler started\")\n\n # Just not to stop this process\n await asyncio.sleep(float(\"inf\"))\n\n async def close(self) -> None:\n closables = [self._socket_mode_client.close(), self._storage_backend.close()]\n await asyncio.gather(*closables)", "n_imports_parsed": 8, "n_files_resolved": 6, "n_chars_extracted": 15759}, "tests/test_setup.py::30": {"resolved_imports": ["src/machine/core.py", "src/machine/storage/backends/memory.py"], "used_names": ["Machine", "MemoryStorage", "pytest"], "enclosing_function": "test_setup", "extracted_code": "# Source: src/machine/core.py\nclass Machine:\n _socket_mode_client: SocketModeClient\n _client: SlackClient | None\n _storage_backend: MachineBaseStorage\n _settings: CaseInsensitiveDict | None\n _help: Manual\n _registered_actions: RegisteredActions\n _tz: ZoneInfo\n _scheduler: AsyncIOScheduler\n\n def __init__(self, settings: CaseInsensitiveDict | None = None):\n if settings is not None:\n self._settings = settings\n else:\n self._settings = None\n self._help = Manual(human={}, robot={})\n self._registered_actions = RegisteredActions()\n self._client = None\n\n async def _setup(self) -> None:\n logger.info(\"Initializing Slack Machine...\")\n\n found_local_settings = self._load_settings()\n assert self._settings is not None\n configure_logging(self._settings)\n if not found_local_settings:\n logger.warning(\"No local_settings found! Are you sure this is what you want?\")\n else:\n logger.debug(\"Found local settings %s\", self._settings)\n\n # Check if Slack token are present\n if \"SLACK_APP_TOKEN\" not in self._settings:\n logger.error(\"No SLACK_APP_TOKEN found in settings! I need that to work...\")\n sys.exit(1)\n if \"SLACK_BOT_TOKEN\" not in self._settings:\n logger.error(\"No SLACK_BOT_TOKEN found in settings! I need that to work...\")\n sys.exit(1)\n\n # Setup storage\n await self._setup_storage()\n\n # Setup Slack clients\n await self._setup_slack_clients()\n\n # Setup scheduling\n self._scheduler = AsyncIOScheduler(timezone=self._tz)\n\n # Load plugins\n await self._load_plugins()\n logger.debug(\"Registered plugin actions: %s\", self._registered_actions)\n logger.debug(\"Plugin help: %s\", self._help)\n\n def _load_settings(self) -> bool:\n logger.info(\"Loading settings...\")\n if self._settings is not None:\n found_local_settings = True\n else:\n settings_module = os.environ.get(\"SM_SETTINGS_MODULE\", \"local_settings\")\n self._settings, found_local_settings = import_settings(settings_module=settings_module)\n self._tz = ZoneInfo(self._settings[\"TZ\"])\n logger.info(\"Settings loaded!\")\n return found_local_settings\n\n async def _setup_storage(self) -> None:\n assert self._settings is not None\n storage_backend = self._settings.get(\"STORAGE_BACKEND\", \"machine.storage.backends.memory.MemoryStorage\")\n logger.info(\"Initializing storage backend %s...\", storage_backend)\n _, cls = import_string(storage_backend)[0]\n self._storage_backend = cls(self._settings)\n await self._storage_backend.init()\n logger.info(\"Storage backend %s initialized!\", storage_backend)\n\n async def _setup_slack_clients(self) -> None:\n assert self._settings is not None\n # Setup Slack socket mode client\n self._socket_mode_client = SocketModeClient(\n app_token=self._settings[\"SLACK_APP_TOKEN\"],\n web_client=AsyncWebClient(token=self._settings[\"SLACK_BOT_TOKEN\"]),\n proxy=self._settings[\"HTTP_PROXY\"],\n )\n\n # Setup high-level Slack client for plugins\n self._client = SlackClient(self._socket_mode_client, self._tz)\n await self._client.setup()\n\n # TODO: factor out plugin registration in separate class / set of functions\n async def _load_plugins(self) -> None:\n assert self._settings is not None\n if self._client is None:\n logger.error(\"Slack client not initialized!\")\n sys.exit(1)\n logger.debug(\"PLUGINS: %s\", self._settings[\"PLUGINS\"])\n for plugin in self._settings[\"PLUGINS\"]:\n for class_name, cls in import_string(plugin):\n if issubclass(cls, MachineBasePlugin) and cls is not MachineBasePlugin:\n logger.debug(\"Found a Machine plugin: %s\", plugin)\n storage = PluginStorage(class_name, self._storage_backend)\n instance = cls(self._client, self._settings, storage)\n missing_settings = self._register_plugin(class_name, instance)\n if missing_settings:\n logger.warning(\"Error loading plugin %s\", class_name)\n error_msg = f\"The following settings are missing: {', '.join(missing_settings)}\"\n logger.warning(error_msg)\n del instance\n else:\n await instance.init()\n logger.info(\"Plugin %s loaded\", class_name)\n await self._storage_backend.set(\"manual\", dill.dumps(self._help))\n\n def _register_plugin(self, plugin_class_name: str, cls_instance: MachineBasePlugin) -> list[str] | None:\n missing_settings = []\n cls_instance_for_missing_settings = cast(DecoratedPluginFunc, cls_instance)\n missing_settings.extend(self._check_missing_settings(cls_instance_for_missing_settings))\n methods = inspect.getmembers(cls_instance, predicate=inspect.ismethod)\n for _, fn in methods:\n method_for_missing_settings = cast(DecoratedPluginFunc, fn)\n missing_settings.extend(self._check_missing_settings(method_for_missing_settings))\n if missing_settings:\n return missing_settings\n\n class_help = cls_instance.__doc__.splitlines()[0] if cls_instance.__doc__ else plugin_class_name\n self._help.human[class_help] = self._help.human.get(class_help, {})\n self._help.robot[class_help] = self._help.robot.get(class_help, [])\n for name, fn in methods:\n if hasattr(fn, \"metadata\"):\n self._register_plugin_actions(plugin_class_name, fn.metadata, cls_instance, name, fn, class_help)\n return None\n\n def _check_missing_settings(self, fn_or_class: DecoratedPluginFunc) -> list[str]:\n missing_settings = []\n if hasattr(fn_or_class, \"metadata\") and isinstance(fn_or_class.metadata, Metadata):\n for setting in fn_or_class.metadata.required_settings:\n if self._settings is None or setting not in self._settings:\n missing_settings.append(setting.upper())\n return missing_settings\n\n def _register_plugin_actions(\n self,\n plugin_class_name: str,\n metadata: Metadata,\n cls_instance: MachineBasePlugin,\n fn_name: str,\n fn: Callable[..., Awaitable[None]],\n class_help: str,\n ) -> None:\n fq_fn_name = f\"{plugin_class_name}.{fn_name}\"\n if fn.__doc__:\n self._help.human[class_help][fq_fn_name] = self._parse_human_help(fn.__doc__)\n for matcher_config in metadata.plugin_actions.listen_to:\n self._register_message_handler(\n type_=\"listen_to\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n matcher_config=matcher_config,\n class_help=class_help,\n )\n for matcher_config in metadata.plugin_actions.respond_to:\n self._register_message_handler(\n type_=\"respond_to\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n matcher_config=matcher_config,\n class_help=class_help,\n )\n for event in metadata.plugin_actions.process:\n self._registered_actions.process[event] = self._registered_actions.process.get(event, {})\n key = f\"{fq_fn_name}-{event}\"\n self._registered_actions.process[event][key] = fn\n for command_config in metadata.plugin_actions.commands:\n self._register_command_handler(\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n command_config=command_config,\n class_help=class_help,\n )\n for block_action_config in metadata.plugin_actions.actions:\n self._register_block_action_handler(\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n block_action_config=block_action_config,\n class_help=class_help,\n )\n for modal_config in metadata.plugin_actions.modal_submissions:\n self._register_modal_handler(\n type_=\"modal\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n modal_config=modal_config,\n class_help=class_help,\n )\n for modal_config in metadata.plugin_actions.modal_closures:\n self._register_modal_handler(\n type_=\"modal_closed\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n modal_config=modal_config,\n class_help=class_help,\n )\n\n if metadata.plugin_actions.schedule is not None:\n self._scheduler.add_job(\n fn,\n trigger=\"cron\",\n args=[],\n id=fq_fn_name,\n replace_existing=True,\n **metadata.plugin_actions.schedule,\n )\n\n def _register_message_handler(\n self,\n type_: Literal[\"listen_to\", \"respond_to\"],\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n matcher_config: MatcherConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n handler = MessageHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n regex=matcher_config.regex,\n handle_message_changed=matcher_config.handle_changed_message,\n )\n key = f\"{fq_fn_name}-{matcher_config.regex.pattern}\"\n getattr(self._registered_actions, type_)[key] = handler\n self._help.robot[class_help].append(self._parse_robot_help(matcher_config, type_))\n\n def _register_command_handler(\n self,\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n command_config: CommandConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n logger.debug(\"signature of command handler\", signature=signature, function=fq_fn_name)\n handler = CommandHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n command=command_config.command,\n is_generator=command_config.is_generator,\n )\n command = command_config.command\n if command in self._registered_actions.command:\n logger.warning(\"command was already defined, previous handler will be overwritten!\", command=command)\n self._registered_actions.command[command] = handler\n # TODO: add to help\n\n def _register_block_action_handler(\n self,\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n block_action_config: ActionConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n logger.debug(\"signature of block action handler\", signature=signature, function=fq_fn_name)\n handler = BlockActionHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n action_id_matcher=block_action_config.action_id,\n block_id_matcher=block_action_config.block_id,\n )\n action_id = matcher_to_str(block_action_config.action_id)\n block_id = matcher_to_str(block_action_config.block_id)\n key = f\"{fq_fn_name}-{action_id}-{block_id}\"\n self._registered_actions.block_actions[key] = handler\n\n def _register_modal_handler(\n self,\n type_: Literal[\"modal\", \"modal_closed\"],\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n modal_config: ModalConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n logger.debug(\"signature of modal handler\", signature=signature, function=fq_fn_name)\n handler = ModalHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n callback_id_matcher=modal_config.callback_id,\n is_generator=modal_config.is_generator,\n )\n key = f\"{fq_fn_name}-{matcher_to_str(modal_config.callback_id)}\"\n getattr(self._registered_actions, type_)[key] = handler\n\n @staticmethod\n def _parse_human_help(doc: str) -> HumanHelp:\n summary = doc.splitlines()[0].split(\":\")\n if len(summary) > 1:\n command = summary[0].strip()\n cmd_help = summary[1].strip()\n else:\n command = \"??\"\n cmd_help = summary[0].strip()\n return HumanHelp(command=command, help=cmd_help)\n\n @staticmethod\n def _parse_robot_help(matcher_config: MatcherConfig, action: str) -> str:\n handle_message_changed_suffix = \" [includes changed messages]\" if matcher_config.handle_changed_message else \"\"\n if action == \"respond_to\":\n return f\"@botname {matcher_config.regex.pattern}{handle_message_changed_suffix}\"\n else:\n return f\"{matcher_config.regex.pattern}{handle_message_changed_suffix}\"\n\n async def run(self) -> None:\n await self._setup()\n assert self._settings is not None\n if self._client is None:\n logger.error(\"Slack client not initialized!\")\n sys.exit(1)\n\n bot_id = self._client.bot_info[\"user_id\"]\n bot_name = self._client.bot_info[\"name\"]\n\n if self._settings.get(\"LOGLEVEL\", \"ERROR\").upper() == \"DEBUG\":\n self._client.register_handler(log_request)\n\n message_handler = create_message_handler(\n self._registered_actions, self._settings, bot_id, bot_name, self._client\n )\n generic_event_handler = create_generic_event_handler(self._registered_actions)\n slash_command_handler = create_slash_command_handler(self._registered_actions, self._client)\n block_action_handler = create_interactive_handler(self._registered_actions, self._client)\n\n self._client.register_handler(message_handler)\n self._client.register_handler(generic_event_handler)\n self._client.register_handler(slash_command_handler)\n self._client.register_handler(block_action_handler)\n # Establish a WebSocket connection to the Socket Mode servers\n await self._socket_mode_client.connect()\n logger.info(\"Connected to Slack\")\n\n self._scheduler.start()\n logger.info(\"Scheduler started\")\n\n # Just not to stop this process\n await asyncio.sleep(float(\"inf\"))\n\n async def close(self) -> None:\n closables = [self._socket_mode_client.close(), self._storage_backend.close()]\n await asyncio.gather(*closables)\n\n\n# Source: src/machine/storage/backends/memory.py\nclass MemoryStorage(MachineBaseStorage):\n _storage: dict[str, tuple[bytes, datetime | None]]\n\n def __init__(self, settings: Mapping[str, Any]):\n super().__init__(settings)\n self._storage = {}\n\n async def get(self, key: str) -> bytes | None:\n stored = self._storage.get(key, None)\n if stored is None:\n return None\n else:\n if stored[1] and stored[1] < datetime.utcnow():\n del self._storage[key]\n return None\n else:\n return stored[0]\n\n async def set(self, key: str, value: bytes, expires: int | None = None) -> None:\n expires_at = datetime.utcnow() + timedelta(seconds=expires) if expires else None\n self._storage[key] = (value, expires_at)\n\n async def has(self, key: str) -> bool:\n stored = self._storage.get(key, None)\n if stored is None:\n return False\n else:\n if stored[1] and stored[1] < datetime.utcnow():\n del self._storage[key]\n return False\n else:\n return True\n\n async def delete(self, key: str) -> None:\n del self._storage[key]\n\n async def size(self) -> int:\n return sys.getsizeof(self._storage) # pragma: no cover\n\n async def close(self) -> None:\n pass", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 17142}, "tests/test_setup.py::34": {"resolved_imports": ["src/machine/core.py", "src/machine/storage/backends/memory.py"], "used_names": ["Machine", "MemoryStorage", "pytest"], "enclosing_function": "test_setup", "extracted_code": "# Source: src/machine/core.py\nclass Machine:\n _socket_mode_client: SocketModeClient\n _client: SlackClient | None\n _storage_backend: MachineBaseStorage\n _settings: CaseInsensitiveDict | None\n _help: Manual\n _registered_actions: RegisteredActions\n _tz: ZoneInfo\n _scheduler: AsyncIOScheduler\n\n def __init__(self, settings: CaseInsensitiveDict | None = None):\n if settings is not None:\n self._settings = settings\n else:\n self._settings = None\n self._help = Manual(human={}, robot={})\n self._registered_actions = RegisteredActions()\n self._client = None\n\n async def _setup(self) -> None:\n logger.info(\"Initializing Slack Machine...\")\n\n found_local_settings = self._load_settings()\n assert self._settings is not None\n configure_logging(self._settings)\n if not found_local_settings:\n logger.warning(\"No local_settings found! Are you sure this is what you want?\")\n else:\n logger.debug(\"Found local settings %s\", self._settings)\n\n # Check if Slack token are present\n if \"SLACK_APP_TOKEN\" not in self._settings:\n logger.error(\"No SLACK_APP_TOKEN found in settings! I need that to work...\")\n sys.exit(1)\n if \"SLACK_BOT_TOKEN\" not in self._settings:\n logger.error(\"No SLACK_BOT_TOKEN found in settings! I need that to work...\")\n sys.exit(1)\n\n # Setup storage\n await self._setup_storage()\n\n # Setup Slack clients\n await self._setup_slack_clients()\n\n # Setup scheduling\n self._scheduler = AsyncIOScheduler(timezone=self._tz)\n\n # Load plugins\n await self._load_plugins()\n logger.debug(\"Registered plugin actions: %s\", self._registered_actions)\n logger.debug(\"Plugin help: %s\", self._help)\n\n def _load_settings(self) -> bool:\n logger.info(\"Loading settings...\")\n if self._settings is not None:\n found_local_settings = True\n else:\n settings_module = os.environ.get(\"SM_SETTINGS_MODULE\", \"local_settings\")\n self._settings, found_local_settings = import_settings(settings_module=settings_module)\n self._tz = ZoneInfo(self._settings[\"TZ\"])\n logger.info(\"Settings loaded!\")\n return found_local_settings\n\n async def _setup_storage(self) -> None:\n assert self._settings is not None\n storage_backend = self._settings.get(\"STORAGE_BACKEND\", \"machine.storage.backends.memory.MemoryStorage\")\n logger.info(\"Initializing storage backend %s...\", storage_backend)\n _, cls = import_string(storage_backend)[0]\n self._storage_backend = cls(self._settings)\n await self._storage_backend.init()\n logger.info(\"Storage backend %s initialized!\", storage_backend)\n\n async def _setup_slack_clients(self) -> None:\n assert self._settings is not None\n # Setup Slack socket mode client\n self._socket_mode_client = SocketModeClient(\n app_token=self._settings[\"SLACK_APP_TOKEN\"],\n web_client=AsyncWebClient(token=self._settings[\"SLACK_BOT_TOKEN\"]),\n proxy=self._settings[\"HTTP_PROXY\"],\n )\n\n # Setup high-level Slack client for plugins\n self._client = SlackClient(self._socket_mode_client, self._tz)\n await self._client.setup()\n\n # TODO: factor out plugin registration in separate class / set of functions\n async def _load_plugins(self) -> None:\n assert self._settings is not None\n if self._client is None:\n logger.error(\"Slack client not initialized!\")\n sys.exit(1)\n logger.debug(\"PLUGINS: %s\", self._settings[\"PLUGINS\"])\n for plugin in self._settings[\"PLUGINS\"]:\n for class_name, cls in import_string(plugin):\n if issubclass(cls, MachineBasePlugin) and cls is not MachineBasePlugin:\n logger.debug(\"Found a Machine plugin: %s\", plugin)\n storage = PluginStorage(class_name, self._storage_backend)\n instance = cls(self._client, self._settings, storage)\n missing_settings = self._register_plugin(class_name, instance)\n if missing_settings:\n logger.warning(\"Error loading plugin %s\", class_name)\n error_msg = f\"The following settings are missing: {', '.join(missing_settings)}\"\n logger.warning(error_msg)\n del instance\n else:\n await instance.init()\n logger.info(\"Plugin %s loaded\", class_name)\n await self._storage_backend.set(\"manual\", dill.dumps(self._help))\n\n def _register_plugin(self, plugin_class_name: str, cls_instance: MachineBasePlugin) -> list[str] | None:\n missing_settings = []\n cls_instance_for_missing_settings = cast(DecoratedPluginFunc, cls_instance)\n missing_settings.extend(self._check_missing_settings(cls_instance_for_missing_settings))\n methods = inspect.getmembers(cls_instance, predicate=inspect.ismethod)\n for _, fn in methods:\n method_for_missing_settings = cast(DecoratedPluginFunc, fn)\n missing_settings.extend(self._check_missing_settings(method_for_missing_settings))\n if missing_settings:\n return missing_settings\n\n class_help = cls_instance.__doc__.splitlines()[0] if cls_instance.__doc__ else plugin_class_name\n self._help.human[class_help] = self._help.human.get(class_help, {})\n self._help.robot[class_help] = self._help.robot.get(class_help, [])\n for name, fn in methods:\n if hasattr(fn, \"metadata\"):\n self._register_plugin_actions(plugin_class_name, fn.metadata, cls_instance, name, fn, class_help)\n return None\n\n def _check_missing_settings(self, fn_or_class: DecoratedPluginFunc) -> list[str]:\n missing_settings = []\n if hasattr(fn_or_class, \"metadata\") and isinstance(fn_or_class.metadata, Metadata):\n for setting in fn_or_class.metadata.required_settings:\n if self._settings is None or setting not in self._settings:\n missing_settings.append(setting.upper())\n return missing_settings\n\n def _register_plugin_actions(\n self,\n plugin_class_name: str,\n metadata: Metadata,\n cls_instance: MachineBasePlugin,\n fn_name: str,\n fn: Callable[..., Awaitable[None]],\n class_help: str,\n ) -> None:\n fq_fn_name = f\"{plugin_class_name}.{fn_name}\"\n if fn.__doc__:\n self._help.human[class_help][fq_fn_name] = self._parse_human_help(fn.__doc__)\n for matcher_config in metadata.plugin_actions.listen_to:\n self._register_message_handler(\n type_=\"listen_to\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n matcher_config=matcher_config,\n class_help=class_help,\n )\n for matcher_config in metadata.plugin_actions.respond_to:\n self._register_message_handler(\n type_=\"respond_to\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n matcher_config=matcher_config,\n class_help=class_help,\n )\n for event in metadata.plugin_actions.process:\n self._registered_actions.process[event] = self._registered_actions.process.get(event, {})\n key = f\"{fq_fn_name}-{event}\"\n self._registered_actions.process[event][key] = fn\n for command_config in metadata.plugin_actions.commands:\n self._register_command_handler(\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n command_config=command_config,\n class_help=class_help,\n )\n for block_action_config in metadata.plugin_actions.actions:\n self._register_block_action_handler(\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n block_action_config=block_action_config,\n class_help=class_help,\n )\n for modal_config in metadata.plugin_actions.modal_submissions:\n self._register_modal_handler(\n type_=\"modal\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n modal_config=modal_config,\n class_help=class_help,\n )\n for modal_config in metadata.plugin_actions.modal_closures:\n self._register_modal_handler(\n type_=\"modal_closed\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n modal_config=modal_config,\n class_help=class_help,\n )\n\n if metadata.plugin_actions.schedule is not None:\n self._scheduler.add_job(\n fn,\n trigger=\"cron\",\n args=[],\n id=fq_fn_name,\n replace_existing=True,\n **metadata.plugin_actions.schedule,\n )\n\n def _register_message_handler(\n self,\n type_: Literal[\"listen_to\", \"respond_to\"],\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n matcher_config: MatcherConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n handler = MessageHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n regex=matcher_config.regex,\n handle_message_changed=matcher_config.handle_changed_message,\n )\n key = f\"{fq_fn_name}-{matcher_config.regex.pattern}\"\n getattr(self._registered_actions, type_)[key] = handler\n self._help.robot[class_help].append(self._parse_robot_help(matcher_config, type_))\n\n def _register_command_handler(\n self,\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n command_config: CommandConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n logger.debug(\"signature of command handler\", signature=signature, function=fq_fn_name)\n handler = CommandHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n command=command_config.command,\n is_generator=command_config.is_generator,\n )\n command = command_config.command\n if command in self._registered_actions.command:\n logger.warning(\"command was already defined, previous handler will be overwritten!\", command=command)\n self._registered_actions.command[command] = handler\n # TODO: add to help\n\n def _register_block_action_handler(\n self,\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n block_action_config: ActionConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n logger.debug(\"signature of block action handler\", signature=signature, function=fq_fn_name)\n handler = BlockActionHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n action_id_matcher=block_action_config.action_id,\n block_id_matcher=block_action_config.block_id,\n )\n action_id = matcher_to_str(block_action_config.action_id)\n block_id = matcher_to_str(block_action_config.block_id)\n key = f\"{fq_fn_name}-{action_id}-{block_id}\"\n self._registered_actions.block_actions[key] = handler\n\n def _register_modal_handler(\n self,\n type_: Literal[\"modal\", \"modal_closed\"],\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n modal_config: ModalConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n logger.debug(\"signature of modal handler\", signature=signature, function=fq_fn_name)\n handler = ModalHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n callback_id_matcher=modal_config.callback_id,\n is_generator=modal_config.is_generator,\n )\n key = f\"{fq_fn_name}-{matcher_to_str(modal_config.callback_id)}\"\n getattr(self._registered_actions, type_)[key] = handler\n\n @staticmethod\n def _parse_human_help(doc: str) -> HumanHelp:\n summary = doc.splitlines()[0].split(\":\")\n if len(summary) > 1:\n command = summary[0].strip()\n cmd_help = summary[1].strip()\n else:\n command = \"??\"\n cmd_help = summary[0].strip()\n return HumanHelp(command=command, help=cmd_help)\n\n @staticmethod\n def _parse_robot_help(matcher_config: MatcherConfig, action: str) -> str:\n handle_message_changed_suffix = \" [includes changed messages]\" if matcher_config.handle_changed_message else \"\"\n if action == \"respond_to\":\n return f\"@botname {matcher_config.regex.pattern}{handle_message_changed_suffix}\"\n else:\n return f\"{matcher_config.regex.pattern}{handle_message_changed_suffix}\"\n\n async def run(self) -> None:\n await self._setup()\n assert self._settings is not None\n if self._client is None:\n logger.error(\"Slack client not initialized!\")\n sys.exit(1)\n\n bot_id = self._client.bot_info[\"user_id\"]\n bot_name = self._client.bot_info[\"name\"]\n\n if self._settings.get(\"LOGLEVEL\", \"ERROR\").upper() == \"DEBUG\":\n self._client.register_handler(log_request)\n\n message_handler = create_message_handler(\n self._registered_actions, self._settings, bot_id, bot_name, self._client\n )\n generic_event_handler = create_generic_event_handler(self._registered_actions)\n slash_command_handler = create_slash_command_handler(self._registered_actions, self._client)\n block_action_handler = create_interactive_handler(self._registered_actions, self._client)\n\n self._client.register_handler(message_handler)\n self._client.register_handler(generic_event_handler)\n self._client.register_handler(slash_command_handler)\n self._client.register_handler(block_action_handler)\n # Establish a WebSocket connection to the Socket Mode servers\n await self._socket_mode_client.connect()\n logger.info(\"Connected to Slack\")\n\n self._scheduler.start()\n logger.info(\"Scheduler started\")\n\n # Just not to stop this process\n await asyncio.sleep(float(\"inf\"))\n\n async def close(self) -> None:\n closables = [self._socket_mode_client.close(), self._storage_backend.close()]\n await asyncio.gather(*closables)\n\n\n# Source: src/machine/storage/backends/memory.py\nclass MemoryStorage(MachineBaseStorage):\n _storage: dict[str, tuple[bytes, datetime | None]]\n\n def __init__(self, settings: Mapping[str, Any]):\n super().__init__(settings)\n self._storage = {}\n\n async def get(self, key: str) -> bytes | None:\n stored = self._storage.get(key, None)\n if stored is None:\n return None\n else:\n if stored[1] and stored[1] < datetime.utcnow():\n del self._storage[key]\n return None\n else:\n return stored[0]\n\n async def set(self, key: str, value: bytes, expires: int | None = None) -> None:\n expires_at = datetime.utcnow() + timedelta(seconds=expires) if expires else None\n self._storage[key] = (value, expires_at)\n\n async def has(self, key: str) -> bool:\n stored = self._storage.get(key, None)\n if stored is None:\n return False\n else:\n if stored[1] and stored[1] < datetime.utcnow():\n del self._storage[key]\n return False\n else:\n return True\n\n async def delete(self, key: str) -> None:\n del self._storage[key]\n\n async def size(self) -> int:\n return sys.getsizeof(self._storage) # pragma: no cover\n\n async def close(self) -> None:\n pass", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 17142}, "tests/test_setup.py::35": {"resolved_imports": ["src/machine/core.py", "src/machine/storage/backends/memory.py"], "used_names": ["Machine", "MemoryStorage", "pytest"], "enclosing_function": "test_setup", "extracted_code": "# Source: src/machine/core.py\nclass Machine:\n _socket_mode_client: SocketModeClient\n _client: SlackClient | None\n _storage_backend: MachineBaseStorage\n _settings: CaseInsensitiveDict | None\n _help: Manual\n _registered_actions: RegisteredActions\n _tz: ZoneInfo\n _scheduler: AsyncIOScheduler\n\n def __init__(self, settings: CaseInsensitiveDict | None = None):\n if settings is not None:\n self._settings = settings\n else:\n self._settings = None\n self._help = Manual(human={}, robot={})\n self._registered_actions = RegisteredActions()\n self._client = None\n\n async def _setup(self) -> None:\n logger.info(\"Initializing Slack Machine...\")\n\n found_local_settings = self._load_settings()\n assert self._settings is not None\n configure_logging(self._settings)\n if not found_local_settings:\n logger.warning(\"No local_settings found! Are you sure this is what you want?\")\n else:\n logger.debug(\"Found local settings %s\", self._settings)\n\n # Check if Slack token are present\n if \"SLACK_APP_TOKEN\" not in self._settings:\n logger.error(\"No SLACK_APP_TOKEN found in settings! I need that to work...\")\n sys.exit(1)\n if \"SLACK_BOT_TOKEN\" not in self._settings:\n logger.error(\"No SLACK_BOT_TOKEN found in settings! I need that to work...\")\n sys.exit(1)\n\n # Setup storage\n await self._setup_storage()\n\n # Setup Slack clients\n await self._setup_slack_clients()\n\n # Setup scheduling\n self._scheduler = AsyncIOScheduler(timezone=self._tz)\n\n # Load plugins\n await self._load_plugins()\n logger.debug(\"Registered plugin actions: %s\", self._registered_actions)\n logger.debug(\"Plugin help: %s\", self._help)\n\n def _load_settings(self) -> bool:\n logger.info(\"Loading settings...\")\n if self._settings is not None:\n found_local_settings = True\n else:\n settings_module = os.environ.get(\"SM_SETTINGS_MODULE\", \"local_settings\")\n self._settings, found_local_settings = import_settings(settings_module=settings_module)\n self._tz = ZoneInfo(self._settings[\"TZ\"])\n logger.info(\"Settings loaded!\")\n return found_local_settings\n\n async def _setup_storage(self) -> None:\n assert self._settings is not None\n storage_backend = self._settings.get(\"STORAGE_BACKEND\", \"machine.storage.backends.memory.MemoryStorage\")\n logger.info(\"Initializing storage backend %s...\", storage_backend)\n _, cls = import_string(storage_backend)[0]\n self._storage_backend = cls(self._settings)\n await self._storage_backend.init()\n logger.info(\"Storage backend %s initialized!\", storage_backend)\n\n async def _setup_slack_clients(self) -> None:\n assert self._settings is not None\n # Setup Slack socket mode client\n self._socket_mode_client = SocketModeClient(\n app_token=self._settings[\"SLACK_APP_TOKEN\"],\n web_client=AsyncWebClient(token=self._settings[\"SLACK_BOT_TOKEN\"]),\n proxy=self._settings[\"HTTP_PROXY\"],\n )\n\n # Setup high-level Slack client for plugins\n self._client = SlackClient(self._socket_mode_client, self._tz)\n await self._client.setup()\n\n # TODO: factor out plugin registration in separate class / set of functions\n async def _load_plugins(self) -> None:\n assert self._settings is not None\n if self._client is None:\n logger.error(\"Slack client not initialized!\")\n sys.exit(1)\n logger.debug(\"PLUGINS: %s\", self._settings[\"PLUGINS\"])\n for plugin in self._settings[\"PLUGINS\"]:\n for class_name, cls in import_string(plugin):\n if issubclass(cls, MachineBasePlugin) and cls is not MachineBasePlugin:\n logger.debug(\"Found a Machine plugin: %s\", plugin)\n storage = PluginStorage(class_name, self._storage_backend)\n instance = cls(self._client, self._settings, storage)\n missing_settings = self._register_plugin(class_name, instance)\n if missing_settings:\n logger.warning(\"Error loading plugin %s\", class_name)\n error_msg = f\"The following settings are missing: {', '.join(missing_settings)}\"\n logger.warning(error_msg)\n del instance\n else:\n await instance.init()\n logger.info(\"Plugin %s loaded\", class_name)\n await self._storage_backend.set(\"manual\", dill.dumps(self._help))\n\n def _register_plugin(self, plugin_class_name: str, cls_instance: MachineBasePlugin) -> list[str] | None:\n missing_settings = []\n cls_instance_for_missing_settings = cast(DecoratedPluginFunc, cls_instance)\n missing_settings.extend(self._check_missing_settings(cls_instance_for_missing_settings))\n methods = inspect.getmembers(cls_instance, predicate=inspect.ismethod)\n for _, fn in methods:\n method_for_missing_settings = cast(DecoratedPluginFunc, fn)\n missing_settings.extend(self._check_missing_settings(method_for_missing_settings))\n if missing_settings:\n return missing_settings\n\n class_help = cls_instance.__doc__.splitlines()[0] if cls_instance.__doc__ else plugin_class_name\n self._help.human[class_help] = self._help.human.get(class_help, {})\n self._help.robot[class_help] = self._help.robot.get(class_help, [])\n for name, fn in methods:\n if hasattr(fn, \"metadata\"):\n self._register_plugin_actions(plugin_class_name, fn.metadata, cls_instance, name, fn, class_help)\n return None\n\n def _check_missing_settings(self, fn_or_class: DecoratedPluginFunc) -> list[str]:\n missing_settings = []\n if hasattr(fn_or_class, \"metadata\") and isinstance(fn_or_class.metadata, Metadata):\n for setting in fn_or_class.metadata.required_settings:\n if self._settings is None or setting not in self._settings:\n missing_settings.append(setting.upper())\n return missing_settings\n\n def _register_plugin_actions(\n self,\n plugin_class_name: str,\n metadata: Metadata,\n cls_instance: MachineBasePlugin,\n fn_name: str,\n fn: Callable[..., Awaitable[None]],\n class_help: str,\n ) -> None:\n fq_fn_name = f\"{plugin_class_name}.{fn_name}\"\n if fn.__doc__:\n self._help.human[class_help][fq_fn_name] = self._parse_human_help(fn.__doc__)\n for matcher_config in metadata.plugin_actions.listen_to:\n self._register_message_handler(\n type_=\"listen_to\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n matcher_config=matcher_config,\n class_help=class_help,\n )\n for matcher_config in metadata.plugin_actions.respond_to:\n self._register_message_handler(\n type_=\"respond_to\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n matcher_config=matcher_config,\n class_help=class_help,\n )\n for event in metadata.plugin_actions.process:\n self._registered_actions.process[event] = self._registered_actions.process.get(event, {})\n key = f\"{fq_fn_name}-{event}\"\n self._registered_actions.process[event][key] = fn\n for command_config in metadata.plugin_actions.commands:\n self._register_command_handler(\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n command_config=command_config,\n class_help=class_help,\n )\n for block_action_config in metadata.plugin_actions.actions:\n self._register_block_action_handler(\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n block_action_config=block_action_config,\n class_help=class_help,\n )\n for modal_config in metadata.plugin_actions.modal_submissions:\n self._register_modal_handler(\n type_=\"modal\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n modal_config=modal_config,\n class_help=class_help,\n )\n for modal_config in metadata.plugin_actions.modal_closures:\n self._register_modal_handler(\n type_=\"modal_closed\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n modal_config=modal_config,\n class_help=class_help,\n )\n\n if metadata.plugin_actions.schedule is not None:\n self._scheduler.add_job(\n fn,\n trigger=\"cron\",\n args=[],\n id=fq_fn_name,\n replace_existing=True,\n **metadata.plugin_actions.schedule,\n )\n\n def _register_message_handler(\n self,\n type_: Literal[\"listen_to\", \"respond_to\"],\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n matcher_config: MatcherConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n handler = MessageHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n regex=matcher_config.regex,\n handle_message_changed=matcher_config.handle_changed_message,\n )\n key = f\"{fq_fn_name}-{matcher_config.regex.pattern}\"\n getattr(self._registered_actions, type_)[key] = handler\n self._help.robot[class_help].append(self._parse_robot_help(matcher_config, type_))\n\n def _register_command_handler(\n self,\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n command_config: CommandConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n logger.debug(\"signature of command handler\", signature=signature, function=fq_fn_name)\n handler = CommandHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n command=command_config.command,\n is_generator=command_config.is_generator,\n )\n command = command_config.command\n if command in self._registered_actions.command:\n logger.warning(\"command was already defined, previous handler will be overwritten!\", command=command)\n self._registered_actions.command[command] = handler\n # TODO: add to help\n\n def _register_block_action_handler(\n self,\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n block_action_config: ActionConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n logger.debug(\"signature of block action handler\", signature=signature, function=fq_fn_name)\n handler = BlockActionHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n action_id_matcher=block_action_config.action_id,\n block_id_matcher=block_action_config.block_id,\n )\n action_id = matcher_to_str(block_action_config.action_id)\n block_id = matcher_to_str(block_action_config.block_id)\n key = f\"{fq_fn_name}-{action_id}-{block_id}\"\n self._registered_actions.block_actions[key] = handler\n\n def _register_modal_handler(\n self,\n type_: Literal[\"modal\", \"modal_closed\"],\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n modal_config: ModalConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n logger.debug(\"signature of modal handler\", signature=signature, function=fq_fn_name)\n handler = ModalHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n callback_id_matcher=modal_config.callback_id,\n is_generator=modal_config.is_generator,\n )\n key = f\"{fq_fn_name}-{matcher_to_str(modal_config.callback_id)}\"\n getattr(self._registered_actions, type_)[key] = handler\n\n @staticmethod\n def _parse_human_help(doc: str) -> HumanHelp:\n summary = doc.splitlines()[0].split(\":\")\n if len(summary) > 1:\n command = summary[0].strip()\n cmd_help = summary[1].strip()\n else:\n command = \"??\"\n cmd_help = summary[0].strip()\n return HumanHelp(command=command, help=cmd_help)\n\n @staticmethod\n def _parse_robot_help(matcher_config: MatcherConfig, action: str) -> str:\n handle_message_changed_suffix = \" [includes changed messages]\" if matcher_config.handle_changed_message else \"\"\n if action == \"respond_to\":\n return f\"@botname {matcher_config.regex.pattern}{handle_message_changed_suffix}\"\n else:\n return f\"{matcher_config.regex.pattern}{handle_message_changed_suffix}\"\n\n async def run(self) -> None:\n await self._setup()\n assert self._settings is not None\n if self._client is None:\n logger.error(\"Slack client not initialized!\")\n sys.exit(1)\n\n bot_id = self._client.bot_info[\"user_id\"]\n bot_name = self._client.bot_info[\"name\"]\n\n if self._settings.get(\"LOGLEVEL\", \"ERROR\").upper() == \"DEBUG\":\n self._client.register_handler(log_request)\n\n message_handler = create_message_handler(\n self._registered_actions, self._settings, bot_id, bot_name, self._client\n )\n generic_event_handler = create_generic_event_handler(self._registered_actions)\n slash_command_handler = create_slash_command_handler(self._registered_actions, self._client)\n block_action_handler = create_interactive_handler(self._registered_actions, self._client)\n\n self._client.register_handler(message_handler)\n self._client.register_handler(generic_event_handler)\n self._client.register_handler(slash_command_handler)\n self._client.register_handler(block_action_handler)\n # Establish a WebSocket connection to the Socket Mode servers\n await self._socket_mode_client.connect()\n logger.info(\"Connected to Slack\")\n\n self._scheduler.start()\n logger.info(\"Scheduler started\")\n\n # Just not to stop this process\n await asyncio.sleep(float(\"inf\"))\n\n async def close(self) -> None:\n closables = [self._socket_mode_client.close(), self._storage_backend.close()]\n await asyncio.gather(*closables)\n\n\n# Source: src/machine/storage/backends/memory.py\nclass MemoryStorage(MachineBaseStorage):\n _storage: dict[str, tuple[bytes, datetime | None]]\n\n def __init__(self, settings: Mapping[str, Any]):\n super().__init__(settings)\n self._storage = {}\n\n async def get(self, key: str) -> bytes | None:\n stored = self._storage.get(key, None)\n if stored is None:\n return None\n else:\n if stored[1] and stored[1] < datetime.utcnow():\n del self._storage[key]\n return None\n else:\n return stored[0]\n\n async def set(self, key: str, value: bytes, expires: int | None = None) -> None:\n expires_at = datetime.utcnow() + timedelta(seconds=expires) if expires else None\n self._storage[key] = (value, expires_at)\n\n async def has(self, key: str) -> bool:\n stored = self._storage.get(key, None)\n if stored is None:\n return False\n else:\n if stored[1] and stored[1] < datetime.utcnow():\n del self._storage[key]\n return False\n else:\n return True\n\n async def delete(self, key: str) -> None:\n del self._storage[key]\n\n async def size(self) -> int:\n return sys.getsizeof(self._storage) # pragma: no cover\n\n async def close(self) -> None:\n pass", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 17142}, "tests/test_setup.py::33": {"resolved_imports": ["src/machine/core.py", "src/machine/storage/backends/memory.py"], "used_names": ["Machine", "MemoryStorage", "pytest"], "enclosing_function": "test_setup", "extracted_code": "# Source: src/machine/core.py\nclass Machine:\n _socket_mode_client: SocketModeClient\n _client: SlackClient | None\n _storage_backend: MachineBaseStorage\n _settings: CaseInsensitiveDict | None\n _help: Manual\n _registered_actions: RegisteredActions\n _tz: ZoneInfo\n _scheduler: AsyncIOScheduler\n\n def __init__(self, settings: CaseInsensitiveDict | None = None):\n if settings is not None:\n self._settings = settings\n else:\n self._settings = None\n self._help = Manual(human={}, robot={})\n self._registered_actions = RegisteredActions()\n self._client = None\n\n async def _setup(self) -> None:\n logger.info(\"Initializing Slack Machine...\")\n\n found_local_settings = self._load_settings()\n assert self._settings is not None\n configure_logging(self._settings)\n if not found_local_settings:\n logger.warning(\"No local_settings found! Are you sure this is what you want?\")\n else:\n logger.debug(\"Found local settings %s\", self._settings)\n\n # Check if Slack token are present\n if \"SLACK_APP_TOKEN\" not in self._settings:\n logger.error(\"No SLACK_APP_TOKEN found in settings! I need that to work...\")\n sys.exit(1)\n if \"SLACK_BOT_TOKEN\" not in self._settings:\n logger.error(\"No SLACK_BOT_TOKEN found in settings! I need that to work...\")\n sys.exit(1)\n\n # Setup storage\n await self._setup_storage()\n\n # Setup Slack clients\n await self._setup_slack_clients()\n\n # Setup scheduling\n self._scheduler = AsyncIOScheduler(timezone=self._tz)\n\n # Load plugins\n await self._load_plugins()\n logger.debug(\"Registered plugin actions: %s\", self._registered_actions)\n logger.debug(\"Plugin help: %s\", self._help)\n\n def _load_settings(self) -> bool:\n logger.info(\"Loading settings...\")\n if self._settings is not None:\n found_local_settings = True\n else:\n settings_module = os.environ.get(\"SM_SETTINGS_MODULE\", \"local_settings\")\n self._settings, found_local_settings = import_settings(settings_module=settings_module)\n self._tz = ZoneInfo(self._settings[\"TZ\"])\n logger.info(\"Settings loaded!\")\n return found_local_settings\n\n async def _setup_storage(self) -> None:\n assert self._settings is not None\n storage_backend = self._settings.get(\"STORAGE_BACKEND\", \"machine.storage.backends.memory.MemoryStorage\")\n logger.info(\"Initializing storage backend %s...\", storage_backend)\n _, cls = import_string(storage_backend)[0]\n self._storage_backend = cls(self._settings)\n await self._storage_backend.init()\n logger.info(\"Storage backend %s initialized!\", storage_backend)\n\n async def _setup_slack_clients(self) -> None:\n assert self._settings is not None\n # Setup Slack socket mode client\n self._socket_mode_client = SocketModeClient(\n app_token=self._settings[\"SLACK_APP_TOKEN\"],\n web_client=AsyncWebClient(token=self._settings[\"SLACK_BOT_TOKEN\"]),\n proxy=self._settings[\"HTTP_PROXY\"],\n )\n\n # Setup high-level Slack client for plugins\n self._client = SlackClient(self._socket_mode_client, self._tz)\n await self._client.setup()\n\n # TODO: factor out plugin registration in separate class / set of functions\n async def _load_plugins(self) -> None:\n assert self._settings is not None\n if self._client is None:\n logger.error(\"Slack client not initialized!\")\n sys.exit(1)\n logger.debug(\"PLUGINS: %s\", self._settings[\"PLUGINS\"])\n for plugin in self._settings[\"PLUGINS\"]:\n for class_name, cls in import_string(plugin):\n if issubclass(cls, MachineBasePlugin) and cls is not MachineBasePlugin:\n logger.debug(\"Found a Machine plugin: %s\", plugin)\n storage = PluginStorage(class_name, self._storage_backend)\n instance = cls(self._client, self._settings, storage)\n missing_settings = self._register_plugin(class_name, instance)\n if missing_settings:\n logger.warning(\"Error loading plugin %s\", class_name)\n error_msg = f\"The following settings are missing: {', '.join(missing_settings)}\"\n logger.warning(error_msg)\n del instance\n else:\n await instance.init()\n logger.info(\"Plugin %s loaded\", class_name)\n await self._storage_backend.set(\"manual\", dill.dumps(self._help))\n\n def _register_plugin(self, plugin_class_name: str, cls_instance: MachineBasePlugin) -> list[str] | None:\n missing_settings = []\n cls_instance_for_missing_settings = cast(DecoratedPluginFunc, cls_instance)\n missing_settings.extend(self._check_missing_settings(cls_instance_for_missing_settings))\n methods = inspect.getmembers(cls_instance, predicate=inspect.ismethod)\n for _, fn in methods:\n method_for_missing_settings = cast(DecoratedPluginFunc, fn)\n missing_settings.extend(self._check_missing_settings(method_for_missing_settings))\n if missing_settings:\n return missing_settings\n\n class_help = cls_instance.__doc__.splitlines()[0] if cls_instance.__doc__ else plugin_class_name\n self._help.human[class_help] = self._help.human.get(class_help, {})\n self._help.robot[class_help] = self._help.robot.get(class_help, [])\n for name, fn in methods:\n if hasattr(fn, \"metadata\"):\n self._register_plugin_actions(plugin_class_name, fn.metadata, cls_instance, name, fn, class_help)\n return None\n\n def _check_missing_settings(self, fn_or_class: DecoratedPluginFunc) -> list[str]:\n missing_settings = []\n if hasattr(fn_or_class, \"metadata\") and isinstance(fn_or_class.metadata, Metadata):\n for setting in fn_or_class.metadata.required_settings:\n if self._settings is None or setting not in self._settings:\n missing_settings.append(setting.upper())\n return missing_settings\n\n def _register_plugin_actions(\n self,\n plugin_class_name: str,\n metadata: Metadata,\n cls_instance: MachineBasePlugin,\n fn_name: str,\n fn: Callable[..., Awaitable[None]],\n class_help: str,\n ) -> None:\n fq_fn_name = f\"{plugin_class_name}.{fn_name}\"\n if fn.__doc__:\n self._help.human[class_help][fq_fn_name] = self._parse_human_help(fn.__doc__)\n for matcher_config in metadata.plugin_actions.listen_to:\n self._register_message_handler(\n type_=\"listen_to\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n matcher_config=matcher_config,\n class_help=class_help,\n )\n for matcher_config in metadata.plugin_actions.respond_to:\n self._register_message_handler(\n type_=\"respond_to\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n matcher_config=matcher_config,\n class_help=class_help,\n )\n for event in metadata.plugin_actions.process:\n self._registered_actions.process[event] = self._registered_actions.process.get(event, {})\n key = f\"{fq_fn_name}-{event}\"\n self._registered_actions.process[event][key] = fn\n for command_config in metadata.plugin_actions.commands:\n self._register_command_handler(\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n command_config=command_config,\n class_help=class_help,\n )\n for block_action_config in metadata.plugin_actions.actions:\n self._register_block_action_handler(\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n block_action_config=block_action_config,\n class_help=class_help,\n )\n for modal_config in metadata.plugin_actions.modal_submissions:\n self._register_modal_handler(\n type_=\"modal\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n modal_config=modal_config,\n class_help=class_help,\n )\n for modal_config in metadata.plugin_actions.modal_closures:\n self._register_modal_handler(\n type_=\"modal_closed\",\n class_=cls_instance,\n class_name=plugin_class_name,\n fq_fn_name=fq_fn_name,\n function=fn,\n modal_config=modal_config,\n class_help=class_help,\n )\n\n if metadata.plugin_actions.schedule is not None:\n self._scheduler.add_job(\n fn,\n trigger=\"cron\",\n args=[],\n id=fq_fn_name,\n replace_existing=True,\n **metadata.plugin_actions.schedule,\n )\n\n def _register_message_handler(\n self,\n type_: Literal[\"listen_to\", \"respond_to\"],\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n matcher_config: MatcherConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n handler = MessageHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n regex=matcher_config.regex,\n handle_message_changed=matcher_config.handle_changed_message,\n )\n key = f\"{fq_fn_name}-{matcher_config.regex.pattern}\"\n getattr(self._registered_actions, type_)[key] = handler\n self._help.robot[class_help].append(self._parse_robot_help(matcher_config, type_))\n\n def _register_command_handler(\n self,\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n command_config: CommandConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n logger.debug(\"signature of command handler\", signature=signature, function=fq_fn_name)\n handler = CommandHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n command=command_config.command,\n is_generator=command_config.is_generator,\n )\n command = command_config.command\n if command in self._registered_actions.command:\n logger.warning(\"command was already defined, previous handler will be overwritten!\", command=command)\n self._registered_actions.command[command] = handler\n # TODO: add to help\n\n def _register_block_action_handler(\n self,\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n block_action_config: ActionConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n logger.debug(\"signature of block action handler\", signature=signature, function=fq_fn_name)\n handler = BlockActionHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n action_id_matcher=block_action_config.action_id,\n block_id_matcher=block_action_config.block_id,\n )\n action_id = matcher_to_str(block_action_config.action_id)\n block_id = matcher_to_str(block_action_config.block_id)\n key = f\"{fq_fn_name}-{action_id}-{block_id}\"\n self._registered_actions.block_actions[key] = handler\n\n def _register_modal_handler(\n self,\n type_: Literal[\"modal\", \"modal_closed\"],\n class_: MachineBasePlugin,\n class_name: str,\n fq_fn_name: str,\n function: Callable[..., Awaitable[None]],\n modal_config: ModalConfig,\n class_help: str,\n ) -> None:\n signature = Signature.from_callable(function)\n logger.debug(\"signature of modal handler\", signature=signature, function=fq_fn_name)\n handler = ModalHandler(\n class_=class_,\n class_name=class_name,\n function=function,\n function_signature=signature,\n callback_id_matcher=modal_config.callback_id,\n is_generator=modal_config.is_generator,\n )\n key = f\"{fq_fn_name}-{matcher_to_str(modal_config.callback_id)}\"\n getattr(self._registered_actions, type_)[key] = handler\n\n @staticmethod\n def _parse_human_help(doc: str) -> HumanHelp:\n summary = doc.splitlines()[0].split(\":\")\n if len(summary) > 1:\n command = summary[0].strip()\n cmd_help = summary[1].strip()\n else:\n command = \"??\"\n cmd_help = summary[0].strip()\n return HumanHelp(command=command, help=cmd_help)\n\n @staticmethod\n def _parse_robot_help(matcher_config: MatcherConfig, action: str) -> str:\n handle_message_changed_suffix = \" [includes changed messages]\" if matcher_config.handle_changed_message else \"\"\n if action == \"respond_to\":\n return f\"@botname {matcher_config.regex.pattern}{handle_message_changed_suffix}\"\n else:\n return f\"{matcher_config.regex.pattern}{handle_message_changed_suffix}\"\n\n async def run(self) -> None:\n await self._setup()\n assert self._settings is not None\n if self._client is None:\n logger.error(\"Slack client not initialized!\")\n sys.exit(1)\n\n bot_id = self._client.bot_info[\"user_id\"]\n bot_name = self._client.bot_info[\"name\"]\n\n if self._settings.get(\"LOGLEVEL\", \"ERROR\").upper() == \"DEBUG\":\n self._client.register_handler(log_request)\n\n message_handler = create_message_handler(\n self._registered_actions, self._settings, bot_id, bot_name, self._client\n )\n generic_event_handler = create_generic_event_handler(self._registered_actions)\n slash_command_handler = create_slash_command_handler(self._registered_actions, self._client)\n block_action_handler = create_interactive_handler(self._registered_actions, self._client)\n\n self._client.register_handler(message_handler)\n self._client.register_handler(generic_event_handler)\n self._client.register_handler(slash_command_handler)\n self._client.register_handler(block_action_handler)\n # Establish a WebSocket connection to the Socket Mode servers\n await self._socket_mode_client.connect()\n logger.info(\"Connected to Slack\")\n\n self._scheduler.start()\n logger.info(\"Scheduler started\")\n\n # Just not to stop this process\n await asyncio.sleep(float(\"inf\"))\n\n async def close(self) -> None:\n closables = [self._socket_mode_client.close(), self._storage_backend.close()]\n await asyncio.gather(*closables)\n\n\n# Source: src/machine/storage/backends/memory.py\nclass MemoryStorage(MachineBaseStorage):\n _storage: dict[str, tuple[bytes, datetime | None]]\n\n def __init__(self, settings: Mapping[str, Any]):\n super().__init__(settings)\n self._storage = {}\n\n async def get(self, key: str) -> bytes | None:\n stored = self._storage.get(key, None)\n if stored is None:\n return None\n else:\n if stored[1] and stored[1] < datetime.utcnow():\n del self._storage[key]\n return None\n else:\n return stored[0]\n\n async def set(self, key: str, value: bytes, expires: int | None = None) -> None:\n expires_at = datetime.utcnow() + timedelta(seconds=expires) if expires else None\n self._storage[key] = (value, expires_at)\n\n async def has(self, key: str) -> bool:\n stored = self._storage.get(key, None)\n if stored is None:\n return False\n else:\n if stored[1] and stored[1] < datetime.utcnow():\n del self._storage[key]\n return False\n else:\n return True\n\n async def delete(self, key: str) -> None:\n del self._storage[key]\n\n async def size(self) -> int:\n return sys.getsizeof(self._storage) # pragma: no cover\n\n async def close(self) -> None:\n pass", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 17142}, "tests/clients/test_slack_client.py::114": {"resolved_imports": ["src/machine/clients/slack.py", "src/machine/models/channel.py", "src/machine/models/user.py"], "used_names": [], "enclosing_function": "test_register_handler", "extracted_code": "", "n_imports_parsed": 10, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/clients/test_slack_client.py::120": {"resolved_imports": ["src/machine/clients/slack.py", "src/machine/models/channel.py", "src/machine/models/user.py"], "used_names": [], "enclosing_function": "test_register_handler", "extracted_code": "", "n_imports_parsed": 10, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/clients/test_slack_client.py::103": {"resolved_imports": ["src/machine/clients/slack.py", "src/machine/models/channel.py", "src/machine/models/user.py"], "used_names": ["id_for_user"], "enclosing_function": "test_id_for_user", "extracted_code": "# Source: src/machine/clients/slack.py\ndef id_for_user(user: User | str) -> str:\n if isinstance(user, User):\n return user.id\n else:\n return user", "n_imports_parsed": 10, "n_files_resolved": 3, "n_chars_extracted": 164}, "tests/clients/test_slack_client.py::104": {"resolved_imports": ["src/machine/clients/slack.py", "src/machine/models/channel.py", "src/machine/models/user.py"], "used_names": ["id_for_user"], "enclosing_function": "test_id_for_user", "extracted_code": "# Source: src/machine/clients/slack.py\ndef id_for_user(user: User | str) -> str:\n if isinstance(user, User):\n return user.id\n else:\n return user", "n_imports_parsed": 10, "n_files_resolved": 3, "n_chars_extracted": 164}, "tests/clients/test_slack_client.py::108": {"resolved_imports": ["src/machine/clients/slack.py", "src/machine/models/channel.py", "src/machine/models/user.py"], "used_names": ["id_for_channel"], "enclosing_function": "test_id_for_channel", "extracted_code": "# Source: src/machine/clients/slack.py\ndef id_for_channel(channel: Channel | str) -> str:\n if isinstance(channel, Channel):\n return channel.id\n else:\n return channel", "n_imports_parsed": 10, "n_files_resolved": 3, "n_chars_extracted": 185}, "tests/clients/test_slack_client.py::109": {"resolved_imports": ["src/machine/clients/slack.py", "src/machine/models/channel.py", "src/machine/models/user.py"], "used_names": ["id_for_channel"], "enclosing_function": "test_id_for_channel", "extracted_code": "# Source: src/machine/clients/slack.py\ndef id_for_channel(channel: Channel | str) -> str:\n if isinstance(channel, Channel):\n return channel.id\n else:\n return channel", "n_imports_parsed": 10, "n_files_resolved": 3, "n_chars_extracted": 185}, "tests/clients/test_slack_client.py::234": {"resolved_imports": ["src/machine/clients/slack.py", "src/machine/models/channel.py", "src/machine/models/user.py"], "used_names": ["pytest"], "enclosing_function": "test_process_users_channels_channel_archive", "extracted_code": "", "n_imports_parsed": 10, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/clients/test_slack_client.py::224": {"resolved_imports": ["src/machine/clients/slack.py", "src/machine/models/channel.py", "src/machine/models/user.py"], "used_names": ["pytest"], "enclosing_function": "test_process_users_channels_channel_archive", "extracted_code": "", "n_imports_parsed": 10, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/handlers/test_command_handler.py::10": {"resolved_imports": ["src/machine/handlers/command_handler.py", "src/machine/plugins/command.py"], "used_names": ["Command"], "enclosing_function": "_assert_command", "extracted_code": "# Source: src/machine/plugins/command.py\nclass Command:\n \"\"\"A Slack command that was received by the bot\n\n This class represents a Slack command that was received by the bot and passed to a plugin.\n It contains the text that was included when the command was invoked, and metadata about\n the command, such as the user that invoked the command, the channel the command was invoked\n in.\n\n The `Command` class also contains convenience methods for sending messages in the right\n channel, opening modals etc.\n \"\"\"\n\n # TODO: create proper class for cmd_event\n def __init__(self, client: SlackClient, cmd_payload: dict[str, Any]):\n self._client = client\n self._cmd_payload = cmd_payload\n self._webhook_client = AsyncWebhookClient(self._cmd_payload[\"response_url\"])\n\n @property\n def sender(self) -> User:\n \"\"\"The user that invoked the command\n\n Returns:\n the User that invoked the command\n \"\"\"\n return self._client.users[self._cmd_payload[\"user_id\"]]\n\n @property\n def channel(self) -> Channel:\n \"\"\"The channel the command was invoked in\n\n Returns:\n the Channel the command was invoked in\n \"\"\"\n return self._client.channels[self._cmd_payload[\"channel_id\"]]\n\n @property\n def is_dm(self) -> bool:\n \"\"\"Whether the command was invoked in a DM\n\n Returns:\n `True` if the message was _not_ invoked in a channel or group, `False` otherwise\n \"\"\"\n channel_id = self._cmd_payload[\"channel_id\"]\n return not (channel_id.startswith(\"C\") or channel_id.startswith(\"G\"))\n\n @property\n def text(self) -> str:\n \"\"\"The body of the command (i.e. anything after the command itself)\n\n Returns:\n the body (text) of the command\n \"\"\"\n return self._cmd_payload[\"text\"]\n\n @property\n def command(self) -> str:\n \"\"\"The command that was invoked\n\n Returns:\n the command that was invoked\n \"\"\"\n return self._cmd_payload[\"command\"]\n\n @property\n def response_url(self) -> str:\n \"\"\"The response url associated with the command\n\n This is a unique url for this specific command invocation.\n It can be used for sending messages in response to the command.\n This can only be used 5 times within 30 minutes of receiving the payload.\n\n Returns:\n the response url associated with the command\n \"\"\"\n return self._cmd_payload[\"response_url\"]\n\n @property\n def trigger_id(self) -> str:\n \"\"\"The trigger id associated with the command\n\n The trigger id can be used to trigger modals\n\n Note:\n The `trigger_id` is only valid for 3 seconds after the modal was submitted.\n\n You can use [`open_modal`][machine.plugins.command.Command.open_modal] to open a modal instead of using\n the `trigger_id` directly.\n\n Returns:\n the trigger id associated with the command\n \"\"\"\n return self._cmd_payload[\"trigger_id\"]\n\n async def say(\n self,\n text: str | None = None,\n attachments: Sequence[Attachment] | Sequence[dict[str, Any]] | None = None,\n blocks: Sequence[Block] | Sequence[dict[str, Any]] | None = None,\n ephemeral: bool = True,\n **kwargs: Any,\n ) -> WebhookResponse:\n \"\"\"Send a new message to the channel the command was invoked in\n\n Send a new message to the channel the command was invoked in, using the response_url as a webhook.\n Allows for rich formatting using [blocks] and/or [attachments] . You can provide blocks\n and attachments as Python dicts or you can use the [convenience classes] that the\n underlying slack client provides.\n This will send an ephemeral message by default, only visible to the user that invoked the command.\n You can set `ephemeral` to `False` to make the message visible to everyone in the channel\n Any extra kwargs you provide, will be passed on directly to `AsyncWebhookClient.send()`\n\n [attachments]: https://api.slack.com/docs/message-attachments\n [blocks]: https://api.slack.com/reference/block-kit/blocks\n [convenience classes]: https://github.com/slackapi/python-slack-sdk/tree/main/slack/web/classes\n\n Args:\n text: message text\n attachments: optional attachments (see [attachments](https://api.slack.com/docs/message-attachments))\n blocks: optional blocks (see [blocks](https://api.slack.com/reference/block-kit/blocks))\n ephemeral: `True/False` wether to send the message as an ephemeral message, only\n visible to the sender of the original message\n\n Returns:\n Dictionary deserialized from `AsyncWebhookClient.send()`\n \"\"\"\n response_type = \"ephemeral\" if ephemeral else \"in_channel\"\n\n return await self._webhook_client.send(\n text=text, attachments=attachments, blocks=blocks, response_type=response_type, **kwargs\n )\n\n async def open_modal(\n self,\n view: dict | View,\n **kwargs: Any,\n ) -> AsyncSlackResponse:\n \"\"\"Open a modal in response to the command\n\n Open a modal in response to the command, using the trigger_id that was returned when the command was invoked.\n Any extra kwargs you provide, will be passed on directly to `AsyncWebClient.views_open()`\n\n Note:\n You have to call this method within 3 seconds of receiving the command payload.\n\n Args:\n view: the view to open\n\n Returns:\n Dictionary deserialized from `AsyncWebClient.views_open()`\n \"\"\"\n return await self._client.open_modal(self.trigger_id, view, **kwargs)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 5804}, "tests/handlers/test_command_handler.py::11": {"resolved_imports": ["src/machine/handlers/command_handler.py", "src/machine/plugins/command.py"], "used_names": ["Command"], "enclosing_function": "_assert_command", "extracted_code": "# Source: src/machine/plugins/command.py\nclass Command:\n \"\"\"A Slack command that was received by the bot\n\n This class represents a Slack command that was received by the bot and passed to a plugin.\n It contains the text that was included when the command was invoked, and metadata about\n the command, such as the user that invoked the command, the channel the command was invoked\n in.\n\n The `Command` class also contains convenience methods for sending messages in the right\n channel, opening modals etc.\n \"\"\"\n\n # TODO: create proper class for cmd_event\n def __init__(self, client: SlackClient, cmd_payload: dict[str, Any]):\n self._client = client\n self._cmd_payload = cmd_payload\n self._webhook_client = AsyncWebhookClient(self._cmd_payload[\"response_url\"])\n\n @property\n def sender(self) -> User:\n \"\"\"The user that invoked the command\n\n Returns:\n the User that invoked the command\n \"\"\"\n return self._client.users[self._cmd_payload[\"user_id\"]]\n\n @property\n def channel(self) -> Channel:\n \"\"\"The channel the command was invoked in\n\n Returns:\n the Channel the command was invoked in\n \"\"\"\n return self._client.channels[self._cmd_payload[\"channel_id\"]]\n\n @property\n def is_dm(self) -> bool:\n \"\"\"Whether the command was invoked in a DM\n\n Returns:\n `True` if the message was _not_ invoked in a channel or group, `False` otherwise\n \"\"\"\n channel_id = self._cmd_payload[\"channel_id\"]\n return not (channel_id.startswith(\"C\") or channel_id.startswith(\"G\"))\n\n @property\n def text(self) -> str:\n \"\"\"The body of the command (i.e. anything after the command itself)\n\n Returns:\n the body (text) of the command\n \"\"\"\n return self._cmd_payload[\"text\"]\n\n @property\n def command(self) -> str:\n \"\"\"The command that was invoked\n\n Returns:\n the command that was invoked\n \"\"\"\n return self._cmd_payload[\"command\"]\n\n @property\n def response_url(self) -> str:\n \"\"\"The response url associated with the command\n\n This is a unique url for this specific command invocation.\n It can be used for sending messages in response to the command.\n This can only be used 5 times within 30 minutes of receiving the payload.\n\n Returns:\n the response url associated with the command\n \"\"\"\n return self._cmd_payload[\"response_url\"]\n\n @property\n def trigger_id(self) -> str:\n \"\"\"The trigger id associated with the command\n\n The trigger id can be used to trigger modals\n\n Note:\n The `trigger_id` is only valid for 3 seconds after the modal was submitted.\n\n You can use [`open_modal`][machine.plugins.command.Command.open_modal] to open a modal instead of using\n the `trigger_id` directly.\n\n Returns:\n the trigger id associated with the command\n \"\"\"\n return self._cmd_payload[\"trigger_id\"]\n\n async def say(\n self,\n text: str | None = None,\n attachments: Sequence[Attachment] | Sequence[dict[str, Any]] | None = None,\n blocks: Sequence[Block] | Sequence[dict[str, Any]] | None = None,\n ephemeral: bool = True,\n **kwargs: Any,\n ) -> WebhookResponse:\n \"\"\"Send a new message to the channel the command was invoked in\n\n Send a new message to the channel the command was invoked in, using the response_url as a webhook.\n Allows for rich formatting using [blocks] and/or [attachments] . You can provide blocks\n and attachments as Python dicts or you can use the [convenience classes] that the\n underlying slack client provides.\n This will send an ephemeral message by default, only visible to the user that invoked the command.\n You can set `ephemeral` to `False` to make the message visible to everyone in the channel\n Any extra kwargs you provide, will be passed on directly to `AsyncWebhookClient.send()`\n\n [attachments]: https://api.slack.com/docs/message-attachments\n [blocks]: https://api.slack.com/reference/block-kit/blocks\n [convenience classes]: https://github.com/slackapi/python-slack-sdk/tree/main/slack/web/classes\n\n Args:\n text: message text\n attachments: optional attachments (see [attachments](https://api.slack.com/docs/message-attachments))\n blocks: optional blocks (see [blocks](https://api.slack.com/reference/block-kit/blocks))\n ephemeral: `True/False` wether to send the message as an ephemeral message, only\n visible to the sender of the original message\n\n Returns:\n Dictionary deserialized from `AsyncWebhookClient.send()`\n \"\"\"\n response_type = \"ephemeral\" if ephemeral else \"in_channel\"\n\n return await self._webhook_client.send(\n text=text, attachments=attachments, blocks=blocks, response_type=response_type, **kwargs\n )\n\n async def open_modal(\n self,\n view: dict | View,\n **kwargs: Any,\n ) -> AsyncSlackResponse:\n \"\"\"Open a modal in response to the command\n\n Open a modal in response to the command, using the trigger_id that was returned when the command was invoked.\n Any extra kwargs you provide, will be passed on directly to `AsyncWebClient.views_open()`\n\n Note:\n You have to call this method within 3 seconds of receiving the command payload.\n\n Args:\n view: the view to open\n\n Returns:\n Dictionary deserialized from `AsyncWebClient.views_open()`\n \"\"\"\n return await self._client.open_modal(self.trigger_id, view, **kwargs)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 5804}, "tests/handlers/test_command_handler.py::29": {"resolved_imports": ["src/machine/handlers/command_handler.py", "src/machine/plugins/command.py"], "used_names": ["create_slash_command_handler", "gen_command_request", "pytest"], "enclosing_function": "test_create_slash_command_handler", "extracted_code": "# Source: src/machine/handlers/command_handler.py\ndef create_slash_command_handler(\n plugin_actions: RegisteredActions,\n slack_client: SlackClient,\n) -> Callable[[AsyncBaseSocketModeClient, SocketModeRequest], Awaitable[None]]:\n async def handle_slash_command_request(client: AsyncBaseSocketModeClient, request: SocketModeRequest) -> None:\n if request.type == \"slash_commands\":\n logger.debug(\"slash command received\", payload=request.payload)\n # We only acknowledge request if we know about this command\n if request.payload[\"command\"] in plugin_actions.command:\n cmd = plugin_actions.command[request.payload[\"command\"]]\n command_obj = _gen_command(request.payload, slack_client)\n if \"logger\" in cmd.function_signature.parameters:\n command_logger = create_scoped_logger(\n cmd.class_name,\n cmd.function.__name__,\n user_id=command_obj.sender.id,\n user_name=command_obj.sender.name,\n )\n extra_args = {\"logger\": command_logger}\n else:\n extra_args = {}\n # Check if the handler is a generator. In this case we have an immediate response we can send back\n if cmd.is_generator:\n gen_fn = cast(Callable[..., AsyncGenerator[Union[dict, JsonObject, str], None]], cmd.function)\n logger.debug(\"Slash command handler is generator, returning immediate ack\")\n gen = gen_fn(command_obj, **extra_args)\n # return immediate reponse\n payload = await gen.__anext__()\n ack_response = SocketModeResponse(envelope_id=request.envelope_id, payload=payload)\n await client.send_socket_mode_response(ack_response)\n # Now run the rest of the function\n with contextlib.suppress(StopAsyncIteration):\n await gen.__anext__()\n else:\n ack_response = SocketModeResponse(envelope_id=request.envelope_id)\n await client.send_socket_mode_response(ack_response)\n fn = cast(Callable[..., Awaitable[None]], cmd.function)\n await fn(command_obj, **extra_args)\n\n return handle_slash_command_request", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 2444}, "tests/handlers/test_command_handler.py::17": {"resolved_imports": ["src/machine/handlers/command_handler.py", "src/machine/plugins/command.py"], "used_names": ["Command"], "enclosing_function": "_assert_command", "extracted_code": "# Source: src/machine/plugins/command.py\nclass Command:\n \"\"\"A Slack command that was received by the bot\n\n This class represents a Slack command that was received by the bot and passed to a plugin.\n It contains the text that was included when the command was invoked, and metadata about\n the command, such as the user that invoked the command, the channel the command was invoked\n in.\n\n The `Command` class also contains convenience methods for sending messages in the right\n channel, opening modals etc.\n \"\"\"\n\n # TODO: create proper class for cmd_event\n def __init__(self, client: SlackClient, cmd_payload: dict[str, Any]):\n self._client = client\n self._cmd_payload = cmd_payload\n self._webhook_client = AsyncWebhookClient(self._cmd_payload[\"response_url\"])\n\n @property\n def sender(self) -> User:\n \"\"\"The user that invoked the command\n\n Returns:\n the User that invoked the command\n \"\"\"\n return self._client.users[self._cmd_payload[\"user_id\"]]\n\n @property\n def channel(self) -> Channel:\n \"\"\"The channel the command was invoked in\n\n Returns:\n the Channel the command was invoked in\n \"\"\"\n return self._client.channels[self._cmd_payload[\"channel_id\"]]\n\n @property\n def is_dm(self) -> bool:\n \"\"\"Whether the command was invoked in a DM\n\n Returns:\n `True` if the message was _not_ invoked in a channel or group, `False` otherwise\n \"\"\"\n channel_id = self._cmd_payload[\"channel_id\"]\n return not (channel_id.startswith(\"C\") or channel_id.startswith(\"G\"))\n\n @property\n def text(self) -> str:\n \"\"\"The body of the command (i.e. anything after the command itself)\n\n Returns:\n the body (text) of the command\n \"\"\"\n return self._cmd_payload[\"text\"]\n\n @property\n def command(self) -> str:\n \"\"\"The command that was invoked\n\n Returns:\n the command that was invoked\n \"\"\"\n return self._cmd_payload[\"command\"]\n\n @property\n def response_url(self) -> str:\n \"\"\"The response url associated with the command\n\n This is a unique url for this specific command invocation.\n It can be used for sending messages in response to the command.\n This can only be used 5 times within 30 minutes of receiving the payload.\n\n Returns:\n the response url associated with the command\n \"\"\"\n return self._cmd_payload[\"response_url\"]\n\n @property\n def trigger_id(self) -> str:\n \"\"\"The trigger id associated with the command\n\n The trigger id can be used to trigger modals\n\n Note:\n The `trigger_id` is only valid for 3 seconds after the modal was submitted.\n\n You can use [`open_modal`][machine.plugins.command.Command.open_modal] to open a modal instead of using\n the `trigger_id` directly.\n\n Returns:\n the trigger id associated with the command\n \"\"\"\n return self._cmd_payload[\"trigger_id\"]\n\n async def say(\n self,\n text: str | None = None,\n attachments: Sequence[Attachment] | Sequence[dict[str, Any]] | None = None,\n blocks: Sequence[Block] | Sequence[dict[str, Any]] | None = None,\n ephemeral: bool = True,\n **kwargs: Any,\n ) -> WebhookResponse:\n \"\"\"Send a new message to the channel the command was invoked in\n\n Send a new message to the channel the command was invoked in, using the response_url as a webhook.\n Allows for rich formatting using [blocks] and/or [attachments] . You can provide blocks\n and attachments as Python dicts or you can use the [convenience classes] that the\n underlying slack client provides.\n This will send an ephemeral message by default, only visible to the user that invoked the command.\n You can set `ephemeral` to `False` to make the message visible to everyone in the channel\n Any extra kwargs you provide, will be passed on directly to `AsyncWebhookClient.send()`\n\n [attachments]: https://api.slack.com/docs/message-attachments\n [blocks]: https://api.slack.com/reference/block-kit/blocks\n [convenience classes]: https://github.com/slackapi/python-slack-sdk/tree/main/slack/web/classes\n\n Args:\n text: message text\n attachments: optional attachments (see [attachments](https://api.slack.com/docs/message-attachments))\n blocks: optional blocks (see [blocks](https://api.slack.com/reference/block-kit/blocks))\n ephemeral: `True/False` wether to send the message as an ephemeral message, only\n visible to the sender of the original message\n\n Returns:\n Dictionary deserialized from `AsyncWebhookClient.send()`\n \"\"\"\n response_type = \"ephemeral\" if ephemeral else \"in_channel\"\n\n return await self._webhook_client.send(\n text=text, attachments=attachments, blocks=blocks, response_type=response_type, **kwargs\n )\n\n async def open_modal(\n self,\n view: dict | View,\n **kwargs: Any,\n ) -> AsyncSlackResponse:\n \"\"\"Open a modal in response to the command\n\n Open a modal in response to the command, using the trigger_id that was returned when the command was invoked.\n Any extra kwargs you provide, will be passed on directly to `AsyncWebClient.views_open()`\n\n Note:\n You have to call this method within 3 seconds of receiving the command payload.\n\n Args:\n view: the view to open\n\n Returns:\n Dictionary deserialized from `AsyncWebClient.views_open()`\n \"\"\"\n return await self._client.open_modal(self.trigger_id, view, **kwargs)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 5804}, "tests/handlers/test_command_handler.py::30": {"resolved_imports": ["src/machine/handlers/command_handler.py", "src/machine/plugins/command.py"], "used_names": ["create_slash_command_handler", "gen_command_request", "pytest"], "enclosing_function": "test_create_slash_command_handler", "extracted_code": "# Source: src/machine/handlers/command_handler.py\ndef create_slash_command_handler(\n plugin_actions: RegisteredActions,\n slack_client: SlackClient,\n) -> Callable[[AsyncBaseSocketModeClient, SocketModeRequest], Awaitable[None]]:\n async def handle_slash_command_request(client: AsyncBaseSocketModeClient, request: SocketModeRequest) -> None:\n if request.type == \"slash_commands\":\n logger.debug(\"slash command received\", payload=request.payload)\n # We only acknowledge request if we know about this command\n if request.payload[\"command\"] in plugin_actions.command:\n cmd = plugin_actions.command[request.payload[\"command\"]]\n command_obj = _gen_command(request.payload, slack_client)\n if \"logger\" in cmd.function_signature.parameters:\n command_logger = create_scoped_logger(\n cmd.class_name,\n cmd.function.__name__,\n user_id=command_obj.sender.id,\n user_name=command_obj.sender.name,\n )\n extra_args = {\"logger\": command_logger}\n else:\n extra_args = {}\n # Check if the handler is a generator. In this case we have an immediate response we can send back\n if cmd.is_generator:\n gen_fn = cast(Callable[..., AsyncGenerator[Union[dict, JsonObject, str], None]], cmd.function)\n logger.debug(\"Slash command handler is generator, returning immediate ack\")\n gen = gen_fn(command_obj, **extra_args)\n # return immediate reponse\n payload = await gen.__anext__()\n ack_response = SocketModeResponse(envelope_id=request.envelope_id, payload=payload)\n await client.send_socket_mode_response(ack_response)\n # Now run the rest of the function\n with contextlib.suppress(StopAsyncIteration):\n await gen.__anext__()\n else:\n ack_response = SocketModeResponse(envelope_id=request.envelope_id)\n await client.send_socket_mode_response(ack_response)\n fn = cast(Callable[..., Awaitable[None]], cmd.function)\n await fn(command_obj, **extra_args)\n\n return handle_slash_command_request", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 2444}, "tests/handlers/test_command_handler.py::15": {"resolved_imports": ["src/machine/handlers/command_handler.py", "src/machine/plugins/command.py"], "used_names": ["Command"], "enclosing_function": "_assert_command", "extracted_code": "# Source: src/machine/plugins/command.py\nclass Command:\n \"\"\"A Slack command that was received by the bot\n\n This class represents a Slack command that was received by the bot and passed to a plugin.\n It contains the text that was included when the command was invoked, and metadata about\n the command, such as the user that invoked the command, the channel the command was invoked\n in.\n\n The `Command` class also contains convenience methods for sending messages in the right\n channel, opening modals etc.\n \"\"\"\n\n # TODO: create proper class for cmd_event\n def __init__(self, client: SlackClient, cmd_payload: dict[str, Any]):\n self._client = client\n self._cmd_payload = cmd_payload\n self._webhook_client = AsyncWebhookClient(self._cmd_payload[\"response_url\"])\n\n @property\n def sender(self) -> User:\n \"\"\"The user that invoked the command\n\n Returns:\n the User that invoked the command\n \"\"\"\n return self._client.users[self._cmd_payload[\"user_id\"]]\n\n @property\n def channel(self) -> Channel:\n \"\"\"The channel the command was invoked in\n\n Returns:\n the Channel the command was invoked in\n \"\"\"\n return self._client.channels[self._cmd_payload[\"channel_id\"]]\n\n @property\n def is_dm(self) -> bool:\n \"\"\"Whether the command was invoked in a DM\n\n Returns:\n `True` if the message was _not_ invoked in a channel or group, `False` otherwise\n \"\"\"\n channel_id = self._cmd_payload[\"channel_id\"]\n return not (channel_id.startswith(\"C\") or channel_id.startswith(\"G\"))\n\n @property\n def text(self) -> str:\n \"\"\"The body of the command (i.e. anything after the command itself)\n\n Returns:\n the body (text) of the command\n \"\"\"\n return self._cmd_payload[\"text\"]\n\n @property\n def command(self) -> str:\n \"\"\"The command that was invoked\n\n Returns:\n the command that was invoked\n \"\"\"\n return self._cmd_payload[\"command\"]\n\n @property\n def response_url(self) -> str:\n \"\"\"The response url associated with the command\n\n This is a unique url for this specific command invocation.\n It can be used for sending messages in response to the command.\n This can only be used 5 times within 30 minutes of receiving the payload.\n\n Returns:\n the response url associated with the command\n \"\"\"\n return self._cmd_payload[\"response_url\"]\n\n @property\n def trigger_id(self) -> str:\n \"\"\"The trigger id associated with the command\n\n The trigger id can be used to trigger modals\n\n Note:\n The `trigger_id` is only valid for 3 seconds after the modal was submitted.\n\n You can use [`open_modal`][machine.plugins.command.Command.open_modal] to open a modal instead of using\n the `trigger_id` directly.\n\n Returns:\n the trigger id associated with the command\n \"\"\"\n return self._cmd_payload[\"trigger_id\"]\n\n async def say(\n self,\n text: str | None = None,\n attachments: Sequence[Attachment] | Sequence[dict[str, Any]] | None = None,\n blocks: Sequence[Block] | Sequence[dict[str, Any]] | None = None,\n ephemeral: bool = True,\n **kwargs: Any,\n ) -> WebhookResponse:\n \"\"\"Send a new message to the channel the command was invoked in\n\n Send a new message to the channel the command was invoked in, using the response_url as a webhook.\n Allows for rich formatting using [blocks] and/or [attachments] . You can provide blocks\n and attachments as Python dicts or you can use the [convenience classes] that the\n underlying slack client provides.\n This will send an ephemeral message by default, only visible to the user that invoked the command.\n You can set `ephemeral` to `False` to make the message visible to everyone in the channel\n Any extra kwargs you provide, will be passed on directly to `AsyncWebhookClient.send()`\n\n [attachments]: https://api.slack.com/docs/message-attachments\n [blocks]: https://api.slack.com/reference/block-kit/blocks\n [convenience classes]: https://github.com/slackapi/python-slack-sdk/tree/main/slack/web/classes\n\n Args:\n text: message text\n attachments: optional attachments (see [attachments](https://api.slack.com/docs/message-attachments))\n blocks: optional blocks (see [blocks](https://api.slack.com/reference/block-kit/blocks))\n ephemeral: `True/False` wether to send the message as an ephemeral message, only\n visible to the sender of the original message\n\n Returns:\n Dictionary deserialized from `AsyncWebhookClient.send()`\n \"\"\"\n response_type = \"ephemeral\" if ephemeral else \"in_channel\"\n\n return await self._webhook_client.send(\n text=text, attachments=attachments, blocks=blocks, response_type=response_type, **kwargs\n )\n\n async def open_modal(\n self,\n view: dict | View,\n **kwargs: Any,\n ) -> AsyncSlackResponse:\n \"\"\"Open a modal in response to the command\n\n Open a modal in response to the command, using the trigger_id that was returned when the command was invoked.\n Any extra kwargs you provide, will be passed on directly to `AsyncWebClient.views_open()`\n\n Note:\n You have to call this method within 3 seconds of receiving the command payload.\n\n Args:\n view: the view to open\n\n Returns:\n Dictionary deserialized from `AsyncWebClient.views_open()`\n \"\"\"\n return await self._client.open_modal(self.trigger_id, view, **kwargs)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 5804}, "tests/handlers/test_command_handler.py::45": {"resolved_imports": ["src/machine/handlers/command_handler.py", "src/machine/plugins/command.py"], "used_names": ["create_slash_command_handler", "gen_command_request", "pytest"], "enclosing_function": "test_create_slash_command_handler_generator", "extracted_code": "# Source: src/machine/handlers/command_handler.py\ndef create_slash_command_handler(\n plugin_actions: RegisteredActions,\n slack_client: SlackClient,\n) -> Callable[[AsyncBaseSocketModeClient, SocketModeRequest], Awaitable[None]]:\n async def handle_slash_command_request(client: AsyncBaseSocketModeClient, request: SocketModeRequest) -> None:\n if request.type == \"slash_commands\":\n logger.debug(\"slash command received\", payload=request.payload)\n # We only acknowledge request if we know about this command\n if request.payload[\"command\"] in plugin_actions.command:\n cmd = plugin_actions.command[request.payload[\"command\"]]\n command_obj = _gen_command(request.payload, slack_client)\n if \"logger\" in cmd.function_signature.parameters:\n command_logger = create_scoped_logger(\n cmd.class_name,\n cmd.function.__name__,\n user_id=command_obj.sender.id,\n user_name=command_obj.sender.name,\n )\n extra_args = {\"logger\": command_logger}\n else:\n extra_args = {}\n # Check if the handler is a generator. In this case we have an immediate response we can send back\n if cmd.is_generator:\n gen_fn = cast(Callable[..., AsyncGenerator[Union[dict, JsonObject, str], None]], cmd.function)\n logger.debug(\"Slash command handler is generator, returning immediate ack\")\n gen = gen_fn(command_obj, **extra_args)\n # return immediate reponse\n payload = await gen.__anext__()\n ack_response = SocketModeResponse(envelope_id=request.envelope_id, payload=payload)\n await client.send_socket_mode_response(ack_response)\n # Now run the rest of the function\n with contextlib.suppress(StopAsyncIteration):\n await gen.__anext__()\n else:\n ack_response = SocketModeResponse(envelope_id=request.envelope_id)\n await client.send_socket_mode_response(ack_response)\n fn = cast(Callable[..., Awaitable[None]], cmd.function)\n await fn(command_obj, **extra_args)\n\n return handle_slash_command_request", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 2444}, "tests/handlers/test_event_handler.py::15": {"resolved_imports": ["src/machine/handlers/event_handler.py"], "used_names": ["create_generic_event_handler", "pytest"], "enclosing_function": "test_create_generic_event_handler", "extracted_code": "# Source: src/machine/handlers/event_handler.py\ndef create_generic_event_handler(\n plugin_actions: RegisteredActions,\n) -> Callable[[AsyncBaseSocketModeClient, SocketModeRequest], Awaitable[None]]:\n async def handle_event_request(client: AsyncBaseSocketModeClient, request: SocketModeRequest) -> None:\n if request.type == \"events_api\":\n # Acknowledge the request anyway\n response = SocketModeResponse(envelope_id=request.envelope_id)\n # Don't forget having await for method calls\n await client.send_socket_mode_response(response)\n\n # only process message events\n if request.payload[\"event\"][\"type\"] in plugin_actions.process:\n await dispatch_event_handlers(\n request.payload[\"event\"], list(plugin_actions.process[request.payload[\"event\"][\"type\"]].values())\n )\n\n return handle_event_request", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 920}, "tests/handlers/test_event_handler.py::17": {"resolved_imports": ["src/machine/handlers/event_handler.py"], "used_names": ["create_generic_event_handler", "pytest"], "enclosing_function": "test_create_generic_event_handler", "extracted_code": "# Source: src/machine/handlers/event_handler.py\ndef create_generic_event_handler(\n plugin_actions: RegisteredActions,\n) -> Callable[[AsyncBaseSocketModeClient, SocketModeRequest], Awaitable[None]]:\n async def handle_event_request(client: AsyncBaseSocketModeClient, request: SocketModeRequest) -> None:\n if request.type == \"events_api\":\n # Acknowledge the request anyway\n response = SocketModeResponse(envelope_id=request.envelope_id)\n # Don't forget having await for method calls\n await client.send_socket_mode_response(response)\n\n # only process message events\n if request.payload[\"event\"][\"type\"] in plugin_actions.process:\n await dispatch_event_handlers(\n request.payload[\"event\"], list(plugin_actions.process[request.payload[\"event\"][\"type\"]].values())\n )\n\n return handle_event_request", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 920}, "tests/handlers/test_event_handler.py::21": {"resolved_imports": ["src/machine/handlers/event_handler.py"], "used_names": ["create_generic_event_handler", "pytest"], "enclosing_function": "test_create_generic_event_handler", "extracted_code": "# Source: src/machine/handlers/event_handler.py\ndef create_generic_event_handler(\n plugin_actions: RegisteredActions,\n) -> Callable[[AsyncBaseSocketModeClient, SocketModeRequest], Awaitable[None]]:\n async def handle_event_request(client: AsyncBaseSocketModeClient, request: SocketModeRequest) -> None:\n if request.type == \"events_api\":\n # Acknowledge the request anyway\n response = SocketModeResponse(envelope_id=request.envelope_id)\n # Don't forget having await for method calls\n await client.send_socket_mode_response(response)\n\n # only process message events\n if request.payload[\"event\"][\"type\"] in plugin_actions.process:\n await dispatch_event_handlers(\n request.payload[\"event\"], list(plugin_actions.process[request.payload[\"event\"][\"type\"]].values())\n )\n\n return handle_event_request", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 920}, "tests/handlers/test_interactive_handler.py::26": {"resolved_imports": ["src/machine/handlers/interactive_handler.py", "src/machine/plugins/block_action.py", "src/machine/plugins/modals.py"], "used_names": ["BlockAction", "_gen_block_action_request", "create_interactive_handler", "pytest"], "enclosing_function": "test_create_interactive_handler_for_block_actions", "extracted_code": "# Source: src/machine/handlers/interactive_handler.py\ndef create_interactive_handler(\n plugin_actions: RegisteredActions,\n slack_client: SlackClient,\n) -> Callable[[AsyncBaseSocketModeClient, SocketModeRequest], Awaitable[None]]:\n async def handle_interactive_request(client: AsyncBaseSocketModeClient, request: SocketModeRequest) -> None:\n if request.type == \"interactive\":\n logger.debug(\"interactive trigger received\", payload=request.payload)\n parsed_payload = InteractivePayload.validate_python(request.payload)\n if parsed_payload.type == \"block_actions\":\n # Acknowledge the request\n response = SocketModeResponse(envelope_id=request.envelope_id)\n await client.send_socket_mode_response(response)\n await handle_block_actions(parsed_payload, plugin_actions, slack_client)\n if parsed_payload.type == \"view_submission\":\n await handle_view_submission(parsed_payload, request.envelope_id, client, plugin_actions, slack_client)\n if parsed_payload.type == \"view_closed\":\n # Acknowledge the request\n response = SocketModeResponse(envelope_id=request.envelope_id)\n await client.send_socket_mode_response(response)\n await handle_view_closed(parsed_payload, plugin_actions, slack_client)\n\n return handle_interactive_request\n\n\n# Source: src/machine/plugins/block_action.py\nclass BlockAction:\n \"\"\"A Slack block action that was received by the bot\n\n This class represents a block action that was received by the bot and passed to a plugin.\n Block actions are actions that are triggered by interactions with blocks in Slack messages and modals.\n This class contains metadata about the block action, such as the action that happened that triggered this handler,\n the user that triggered the action, the state of the block when the action was triggered, the payload that was\n received when the action was triggered.\n\n Attributes:\n payload: The payload that was received by the bot when the action was triggered that this\n plugin method listens for\n triggered_action: The action that triggered this plugin method\n \"\"\"\n\n payload: BlockActionsPayload\n triggered_action: Action\n\n def __init__(self, client: SlackClient, payload: BlockActionsPayload, triggered_action: Action):\n self._client = client\n self.payload = payload\n \"\"\"The payload that was received by the bot when the action was triggered that this plugin method listens for\"\"\"\n self.triggered_action = triggered_action\n \"\"\"The action that triggered this plugin method\"\"\"\n self._webhook_client = AsyncWebhookClient(self.payload.response_url) if self.payload.response_url else None\n\n @property\n def user(self) -> User:\n \"\"\"The user that triggered the action\n\n Returns:\n the user that triggered the action\n \"\"\"\n return self._client.users[self.payload.user.id]\n\n @property\n def channel(self) -> Channel | None:\n \"\"\"The channel the action was triggered in\n\n Returns:\n the channel the action was triggered in or None if the action was triggered in a modal\n \"\"\"\n if self.payload.channel is None:\n return None\n return self._client.channels[self.payload.channel.id]\n\n @property\n def state(self) -> State | None:\n \"\"\"The state of the block when the action was triggered\n\n Returns:\n the state of the block when the action was triggered\n \"\"\"\n return self.payload.state\n\n @property\n def response_url(self) -> str | None:\n \"\"\"The response URL for the action\n\n Returns:\n the response URL for the action or `None` if the action was triggered in a modal\n \"\"\"\n return self.payload.response_url\n\n @property\n def trigger_id(self) -> str:\n \"\"\"The trigger id associated with the action\n\n The trigger id can be used to open a modal\n\n Note:\n The `trigger_id` is only valid for 3 seconds after the modal was submitted.\n\n You can use [`open_modal`][machine.plugins.block_action.BlockAction.open_modal] to open a modal instead of\n using the `trigger_id` directly.\n\n Returns:\n the trigger id for the action\n \"\"\"\n return self.payload.trigger_id\n\n async def say(\n self,\n text: str | None = None,\n attachments: Union[Sequence[Attachment], Sequence[dict[str, Any]], None] = None,\n blocks: Union[Sequence[Block], Sequence[dict[str, Any]], None] = None,\n ephemeral: bool = True,\n replace_original: bool = False,\n delete_original: bool = False,\n **kwargs: Any,\n ) -> WebhookResponse | None:\n \"\"\"Send a new message to the channel the block action was triggered in\n\n Send a new message to the channel the block action was triggered in, using the response_url as a webhook.\n If the block action happened in a modal, the response_url will be None and this method will not send a message\n but instead log a warning.\n Allows for rich formatting using [blocks] and/or [attachments]. You can provide blocks\n and attachments as Python dicts or you can use the [convenience classes] that the\n underlying slack client provides.\n This will send an ephemeral message by default, only visible to the user that triggered the action.\n You can set `ephemeral` to `False` to make the message visible to everyone in the channel.\n By default, Slack replaces the original message in which the action was triggered. This method overrides this\n behavior. If you want your message to replace the original, set replace_original to True.\n Any extra kwargs you provide, will be passed on directly to `AsyncWebhookClient.send()`\n\n [attachments]: https://api.slack.com/docs/message-attachments\n [blocks]: https://api.slack.com/reference/block-kit/blocks\n [convenience classes]: https://github.com/slackapi/python-slack-sdk/tree/main/slack/web/classes\n\n Args:\n text: message text\n attachments: optional attachments (see [attachments](https://api.slack.com/docs/message-attachments))\n blocks: optional blocks (see [blocks](https://api.slack.com/docs/message-attachments))\n ephemeral: `True/False` wether to send the message as an ephemeral message, only\n visible to the user that initiated the action\n replace_original: `True/False` whether the message that contains the block from which the action was\n triggered should be replaced by this message\n delete_original: `True/False` whether the message that contains the block from which the action was\n triggered should be deleted. No other parameters should be provided.\n\n Returns:\n Dictionary deserialized from `AsyncWebhookClient.send()`\n\n \"\"\"\n if self._webhook_client is None:\n logger.warning(\n \"response_url is None, cannot send message. This likely means the action was triggered in a modal.\"\n )\n return None\n\n response_type = \"ephemeral\" if ephemeral else \"in_channel\"\n return await self._webhook_client.send(\n text=text,\n attachments=attachments,\n blocks=blocks,\n response_type=response_type,\n replace_original=replace_original,\n delete_original=delete_original,\n **kwargs,\n )\n\n async def send_dm(\n self,\n text: str | None = None,\n attachments: Sequence[Attachment] | Sequence[dict[str, Any]] | None = None,\n blocks: Sequence[Block] | Sequence[dict[str, Any]] | None = None,\n **kwargs: Any,\n ) -> AsyncSlackResponse:\n \"\"\"Send a DM to the user that triggered the block action\n\n Send a Direct Message to the user that triggered the block action by opening a DM channel and\n sending a message to it.\n Allows for rich formatting using [blocks] and/or [attachments]. You can provide blocks\n and attachments as Python dicts or you can use the [convenience classes] that the\n underlying slack client provides.\n Any extra kwargs you provide, will be passed on directly to the `chat.postMessage` request.\n\n [attachments]: https://api.slack.com/docs/message-attachments\n [blocks]: https://api.slack.com/reference/block-kit/blocks\n [convenience classes]: https://github.com/slackapi/python-slack-sdk/tree/main/slack/web/classes\n\n Args:\n text: message text\n attachments: optional attachments (see [attachments](https://api.slack.com/docs/message-attachments))\n blocks: optional blocks (see [blocks](https://api.slack.com/reference/block-kit/blocks))\n\n Returns:\n Dictionary deserialized from [chat.postMessage](https://api.slack.com/methods/chat.postMessage) response.\n \"\"\"\n return await self._client.send_dm(self.user.id, text, attachments=attachments, blocks=blocks, **kwargs)\n\n async def open_modal(\n self,\n view: dict | View,\n **kwargs: Any,\n ) -> AsyncSlackResponse:\n \"\"\"Open a modal in response to the block action\n\n Open a modal in response to the block action, using the trigger_id that was returned when the block action was\n triggered.\n Any extra kwargs you provide, will be passed on directly to\n [views.open](https://api.slack.com/methods/views.open)\n\n Note:\n You have to call this method within 3 seconds of receiving the block action payload.\n\n Args:\n view: the view to open\n\n Returns:\n Dictionary deserialized from [views.open](https://api.slack.com/methods/views.open)\n \"\"\"\n return await self._client.open_modal(self.trigger_id, view, **kwargs)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 10056}, "tests/handlers/test_interactive_handler.py::52": {"resolved_imports": ["src/machine/handlers/interactive_handler.py", "src/machine/plugins/block_action.py", "src/machine/plugins/modals.py"], "used_names": ["ModalSubmission", "_gen_view_submission_request", "create_interactive_handler", "pytest"], "enclosing_function": "test_create_interactive_handler_for_view_submission", "extracted_code": "# Source: src/machine/handlers/interactive_handler.py\ndef create_interactive_handler(\n plugin_actions: RegisteredActions,\n slack_client: SlackClient,\n) -> Callable[[AsyncBaseSocketModeClient, SocketModeRequest], Awaitable[None]]:\n async def handle_interactive_request(client: AsyncBaseSocketModeClient, request: SocketModeRequest) -> None:\n if request.type == \"interactive\":\n logger.debug(\"interactive trigger received\", payload=request.payload)\n parsed_payload = InteractivePayload.validate_python(request.payload)\n if parsed_payload.type == \"block_actions\":\n # Acknowledge the request\n response = SocketModeResponse(envelope_id=request.envelope_id)\n await client.send_socket_mode_response(response)\n await handle_block_actions(parsed_payload, plugin_actions, slack_client)\n if parsed_payload.type == \"view_submission\":\n await handle_view_submission(parsed_payload, request.envelope_id, client, plugin_actions, slack_client)\n if parsed_payload.type == \"view_closed\":\n # Acknowledge the request\n response = SocketModeResponse(envelope_id=request.envelope_id)\n await client.send_socket_mode_response(response)\n await handle_view_closed(parsed_payload, plugin_actions, slack_client)\n\n return handle_interactive_request\n\n\n# Source: src/machine/plugins/modals.py\nclass ModalSubmission:\n \"\"\"A Slack modal submission that was received by the bot\n\n This class represents a modal submission that was received by the bot and passed to a plugin.\n\n Attributes:\n payload: The payload that was received by the bot when the modal was submitted\n \"\"\"\n\n payload: ViewSubmissionPayload\n\n def __init__(self, client: SlackClient, payload: ViewSubmissionPayload):\n self._client = client\n self.payload = payload\n\n @property\n def user(self) -> User:\n \"\"\"The user that submitted the modal\n\n Returns:\n the user that submitted the modal\n \"\"\"\n return self._client.users[self.payload.user.id]\n\n @property\n def view(self) -> View:\n \"\"\"The view that was submitted including the state of all the elements in the view\n\n Returns:\n the view that was submitted\n \"\"\"\n return self.payload.view\n\n @property\n def trigger_id(self) -> str:\n \"\"\"The trigger id associated with the submitted modal\n\n The trigger id can be used to open another modal\n\n Note:\n The trigger id is only valid for 3 seconds after the modal was submitted.\n\n You can use [`open_modal()`][machine.plugins.modals.ModalSubmission.open_modal] to open a modal instead of\n using the `trigger_id` directly.\n\n Returns:\n the trigger id for the modal\n \"\"\"\n return self.payload.trigger_id\n\n async def open_modal(\n self,\n view: dict | SlackSDKView,\n **kwargs: Any,\n ) -> AsyncSlackResponse:\n \"\"\"Open another modal in response to the modal submission\n\n Open another modal in response to modal submission, using the trigger_id that was returned when the modal was\n submitted.\n Any extra kwargs you provide, will be passed on directly to\n [views.open](https://api.slack.com/methods/views.open)\n\n Note:\n You have to call this method within 3 seconds of receiving the modal submission payload.\n\n Args:\n view: the view to open\n\n Returns:\n Dictionary deserialized from [views.open](https://api.slack.com/methods/views.open)\n \"\"\"\n return await self._client.open_modal(self.trigger_id, view, **kwargs)\n\n async def push_modal(\n self,\n view: dict | SlackSDKView,\n **kwargs: Any,\n ) -> AsyncSlackResponse:\n \"\"\"Push a new modal view in response to the modal submission\n\n Push a new modal view on top of the view stack in response to modal submission, using the trigger_id that was\n returned when the modal was submitted.\n Any extra kwargs you provide, will be passed on directly to\n [views.push](https://api.slack.com/methods/views.push)\n\n Note:\n You have to call this method within 3 seconds of receiving the modal submission payload.\n\n Args:\n view: the view to push\n\n Returns:\n Dictionary deserialized from [views.push](https://api.slack.com/methods/views.push)\n \"\"\"\n return await self._client.push_modal(self.trigger_id, view, **kwargs)\n\n async def update_modal(\n self,\n view: dict | SlackSDKView,\n **kwargs: Any,\n ) -> AsyncSlackResponse:\n \"\"\"Update the modal view in response to the modal submission\n\n Update the modal view in response to modal submission, using the trigger_id that was returned when the modal was\n submitted.\n Any extra kwargs you provide, will be passed on directly to\n [views.update](https://api.slack.com/methods/views.update)\n\n Note:\n You have to call this method within 3 seconds of receiving the modal submission payload.\n\n Args:\n view: the view to update\n\n Returns:\n Dictionary deserialized from [views.update](https://api.slack.com/methods/views.update)\n \"\"\"\n return await self._client.update_modal(view, self.payload.view.id, self.payload.view.external_id, **kwargs)\n\n async def send_dm(\n self,\n text: str | None = None,\n attachments: Sequence[Attachment] | Sequence[dict[str, Any]] | None = None,\n blocks: Sequence[Block] | Sequence[dict[str, Any]] | None = None,\n **kwargs: Any,\n ) -> AsyncSlackResponse:\n \"\"\"Send a DM to the user that submitted the modal\n\n Send a Direct Message to the user that submitted the modal by opening a DM channel and\n sending a message to it.\n Allows for rich formatting using [blocks] and/or [attachments] . You can provide blocks\n and attachments as Python dicts or you can use the [convenience classes] that the\n underlying slack client provides.\n Any extra kwargs you provide, will be passed on directly to the\n [chat.postMessage](https://api.slack.com/methods/chat.postMessage) request.\n\n [attachments]: https://api.slack.com/docs/message-attachments\n [blocks]: https://api.slack.com/reference/block-kit/blocks\n [convenience classes]: https://github.com/slackapi/python-slack-sdk/tree/main/slack/web/classes\n\n Args:\n text: message text\n attachments: optional attachments (see [attachments](https://api.slack.com/docs/message-attachments))\n blocks: optional blocks (see [blocks](https://api.slack.com/reference/block-kit/blocks))\n\n Returns:\n Dictionary deserialized from [chat.postMessage](https://api.slack.com/methods/chat.postMessage) response.\n \"\"\"\n return await self._client.send_dm(self.user.id, text, attachments=attachments, blocks=blocks, **kwargs)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 7139}, "tests/handlers/test_interactive_handler.py::33": {"resolved_imports": ["src/machine/handlers/interactive_handler.py", "src/machine/plugins/block_action.py", "src/machine/plugins/modals.py"], "used_names": ["BlockAction", "_gen_block_action_request", "create_interactive_handler", "pytest"], "enclosing_function": "test_create_interactive_handler_for_block_actions", "extracted_code": "# Source: src/machine/handlers/interactive_handler.py\ndef create_interactive_handler(\n plugin_actions: RegisteredActions,\n slack_client: SlackClient,\n) -> Callable[[AsyncBaseSocketModeClient, SocketModeRequest], Awaitable[None]]:\n async def handle_interactive_request(client: AsyncBaseSocketModeClient, request: SocketModeRequest) -> None:\n if request.type == \"interactive\":\n logger.debug(\"interactive trigger received\", payload=request.payload)\n parsed_payload = InteractivePayload.validate_python(request.payload)\n if parsed_payload.type == \"block_actions\":\n # Acknowledge the request\n response = SocketModeResponse(envelope_id=request.envelope_id)\n await client.send_socket_mode_response(response)\n await handle_block_actions(parsed_payload, plugin_actions, slack_client)\n if parsed_payload.type == \"view_submission\":\n await handle_view_submission(parsed_payload, request.envelope_id, client, plugin_actions, slack_client)\n if parsed_payload.type == \"view_closed\":\n # Acknowledge the request\n response = SocketModeResponse(envelope_id=request.envelope_id)\n await client.send_socket_mode_response(response)\n await handle_view_closed(parsed_payload, plugin_actions, slack_client)\n\n return handle_interactive_request\n\n\n# Source: src/machine/plugins/block_action.py\nclass BlockAction:\n \"\"\"A Slack block action that was received by the bot\n\n This class represents a block action that was received by the bot and passed to a plugin.\n Block actions are actions that are triggered by interactions with blocks in Slack messages and modals.\n This class contains metadata about the block action, such as the action that happened that triggered this handler,\n the user that triggered the action, the state of the block when the action was triggered, the payload that was\n received when the action was triggered.\n\n Attributes:\n payload: The payload that was received by the bot when the action was triggered that this\n plugin method listens for\n triggered_action: The action that triggered this plugin method\n \"\"\"\n\n payload: BlockActionsPayload\n triggered_action: Action\n\n def __init__(self, client: SlackClient, payload: BlockActionsPayload, triggered_action: Action):\n self._client = client\n self.payload = payload\n \"\"\"The payload that was received by the bot when the action was triggered that this plugin method listens for\"\"\"\n self.triggered_action = triggered_action\n \"\"\"The action that triggered this plugin method\"\"\"\n self._webhook_client = AsyncWebhookClient(self.payload.response_url) if self.payload.response_url else None\n\n @property\n def user(self) -> User:\n \"\"\"The user that triggered the action\n\n Returns:\n the user that triggered the action\n \"\"\"\n return self._client.users[self.payload.user.id]\n\n @property\n def channel(self) -> Channel | None:\n \"\"\"The channel the action was triggered in\n\n Returns:\n the channel the action was triggered in or None if the action was triggered in a modal\n \"\"\"\n if self.payload.channel is None:\n return None\n return self._client.channels[self.payload.channel.id]\n\n @property\n def state(self) -> State | None:\n \"\"\"The state of the block when the action was triggered\n\n Returns:\n the state of the block when the action was triggered\n \"\"\"\n return self.payload.state\n\n @property\n def response_url(self) -> str | None:\n \"\"\"The response URL for the action\n\n Returns:\n the response URL for the action or `None` if the action was triggered in a modal\n \"\"\"\n return self.payload.response_url\n\n @property\n def trigger_id(self) -> str:\n \"\"\"The trigger id associated with the action\n\n The trigger id can be used to open a modal\n\n Note:\n The `trigger_id` is only valid for 3 seconds after the modal was submitted.\n\n You can use [`open_modal`][machine.plugins.block_action.BlockAction.open_modal] to open a modal instead of\n using the `trigger_id` directly.\n\n Returns:\n the trigger id for the action\n \"\"\"\n return self.payload.trigger_id\n\n async def say(\n self,\n text: str | None = None,\n attachments: Union[Sequence[Attachment], Sequence[dict[str, Any]], None] = None,\n blocks: Union[Sequence[Block], Sequence[dict[str, Any]], None] = None,\n ephemeral: bool = True,\n replace_original: bool = False,\n delete_original: bool = False,\n **kwargs: Any,\n ) -> WebhookResponse | None:\n \"\"\"Send a new message to the channel the block action was triggered in\n\n Send a new message to the channel the block action was triggered in, using the response_url as a webhook.\n If the block action happened in a modal, the response_url will be None and this method will not send a message\n but instead log a warning.\n Allows for rich formatting using [blocks] and/or [attachments]. You can provide blocks\n and attachments as Python dicts or you can use the [convenience classes] that the\n underlying slack client provides.\n This will send an ephemeral message by default, only visible to the user that triggered the action.\n You can set `ephemeral` to `False` to make the message visible to everyone in the channel.\n By default, Slack replaces the original message in which the action was triggered. This method overrides this\n behavior. If you want your message to replace the original, set replace_original to True.\n Any extra kwargs you provide, will be passed on directly to `AsyncWebhookClient.send()`\n\n [attachments]: https://api.slack.com/docs/message-attachments\n [blocks]: https://api.slack.com/reference/block-kit/blocks\n [convenience classes]: https://github.com/slackapi/python-slack-sdk/tree/main/slack/web/classes\n\n Args:\n text: message text\n attachments: optional attachments (see [attachments](https://api.slack.com/docs/message-attachments))\n blocks: optional blocks (see [blocks](https://api.slack.com/docs/message-attachments))\n ephemeral: `True/False` wether to send the message as an ephemeral message, only\n visible to the user that initiated the action\n replace_original: `True/False` whether the message that contains the block from which the action was\n triggered should be replaced by this message\n delete_original: `True/False` whether the message that contains the block from which the action was\n triggered should be deleted. No other parameters should be provided.\n\n Returns:\n Dictionary deserialized from `AsyncWebhookClient.send()`\n\n \"\"\"\n if self._webhook_client is None:\n logger.warning(\n \"response_url is None, cannot send message. This likely means the action was triggered in a modal.\"\n )\n return None\n\n response_type = \"ephemeral\" if ephemeral else \"in_channel\"\n return await self._webhook_client.send(\n text=text,\n attachments=attachments,\n blocks=blocks,\n response_type=response_type,\n replace_original=replace_original,\n delete_original=delete_original,\n **kwargs,\n )\n\n async def send_dm(\n self,\n text: str | None = None,\n attachments: Sequence[Attachment] | Sequence[dict[str, Any]] | None = None,\n blocks: Sequence[Block] | Sequence[dict[str, Any]] | None = None,\n **kwargs: Any,\n ) -> AsyncSlackResponse:\n \"\"\"Send a DM to the user that triggered the block action\n\n Send a Direct Message to the user that triggered the block action by opening a DM channel and\n sending a message to it.\n Allows for rich formatting using [blocks] and/or [attachments]. You can provide blocks\n and attachments as Python dicts or you can use the [convenience classes] that the\n underlying slack client provides.\n Any extra kwargs you provide, will be passed on directly to the `chat.postMessage` request.\n\n [attachments]: https://api.slack.com/docs/message-attachments\n [blocks]: https://api.slack.com/reference/block-kit/blocks\n [convenience classes]: https://github.com/slackapi/python-slack-sdk/tree/main/slack/web/classes\n\n Args:\n text: message text\n attachments: optional attachments (see [attachments](https://api.slack.com/docs/message-attachments))\n blocks: optional blocks (see [blocks](https://api.slack.com/reference/block-kit/blocks))\n\n Returns:\n Dictionary deserialized from [chat.postMessage](https://api.slack.com/methods/chat.postMessage) response.\n \"\"\"\n return await self._client.send_dm(self.user.id, text, attachments=attachments, blocks=blocks, **kwargs)\n\n async def open_modal(\n self,\n view: dict | View,\n **kwargs: Any,\n ) -> AsyncSlackResponse:\n \"\"\"Open a modal in response to the block action\n\n Open a modal in response to the block action, using the trigger_id that was returned when the block action was\n triggered.\n Any extra kwargs you provide, will be passed on directly to\n [views.open](https://api.slack.com/methods/views.open)\n\n Note:\n You have to call this method within 3 seconds of receiving the block action payload.\n\n Args:\n view: the view to open\n\n Returns:\n Dictionary deserialized from [views.open](https://api.slack.com/methods/views.open)\n \"\"\"\n return await self._client.open_modal(self.trigger_id, view, **kwargs)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 10056}, "tests/handlers/test_interactive_handler.py::12": {"resolved_imports": ["src/machine/handlers/interactive_handler.py", "src/machine/plugins/block_action.py", "src/machine/plugins/modals.py"], "used_names": ["_matches", "re"], "enclosing_function": "test_matches", "extracted_code": "# Source: src/machine/handlers/interactive_handler.py\ndef _matches(matcher: Union[re.Pattern[str], str, None], input_: str) -> bool:\n if matcher is None:\n return True\n if isinstance(matcher, re.Pattern):\n return matcher.match(input_) is not None\n return matcher == input_", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 294}, "tests/handlers/test_interactive_handler.py::34": {"resolved_imports": ["src/machine/handlers/interactive_handler.py", "src/machine/plugins/block_action.py", "src/machine/plugins/modals.py"], "used_names": ["BlockAction", "_gen_block_action_request", "create_interactive_handler", "pytest"], "enclosing_function": "test_create_interactive_handler_for_block_actions", "extracted_code": "# Source: src/machine/handlers/interactive_handler.py\ndef create_interactive_handler(\n plugin_actions: RegisteredActions,\n slack_client: SlackClient,\n) -> Callable[[AsyncBaseSocketModeClient, SocketModeRequest], Awaitable[None]]:\n async def handle_interactive_request(client: AsyncBaseSocketModeClient, request: SocketModeRequest) -> None:\n if request.type == \"interactive\":\n logger.debug(\"interactive trigger received\", payload=request.payload)\n parsed_payload = InteractivePayload.validate_python(request.payload)\n if parsed_payload.type == \"block_actions\":\n # Acknowledge the request\n response = SocketModeResponse(envelope_id=request.envelope_id)\n await client.send_socket_mode_response(response)\n await handle_block_actions(parsed_payload, plugin_actions, slack_client)\n if parsed_payload.type == \"view_submission\":\n await handle_view_submission(parsed_payload, request.envelope_id, client, plugin_actions, slack_client)\n if parsed_payload.type == \"view_closed\":\n # Acknowledge the request\n response = SocketModeResponse(envelope_id=request.envelope_id)\n await client.send_socket_mode_response(response)\n await handle_view_closed(parsed_payload, plugin_actions, slack_client)\n\n return handle_interactive_request\n\n\n# Source: src/machine/plugins/block_action.py\nclass BlockAction:\n \"\"\"A Slack block action that was received by the bot\n\n This class represents a block action that was received by the bot and passed to a plugin.\n Block actions are actions that are triggered by interactions with blocks in Slack messages and modals.\n This class contains metadata about the block action, such as the action that happened that triggered this handler,\n the user that triggered the action, the state of the block when the action was triggered, the payload that was\n received when the action was triggered.\n\n Attributes:\n payload: The payload that was received by the bot when the action was triggered that this\n plugin method listens for\n triggered_action: The action that triggered this plugin method\n \"\"\"\n\n payload: BlockActionsPayload\n triggered_action: Action\n\n def __init__(self, client: SlackClient, payload: BlockActionsPayload, triggered_action: Action):\n self._client = client\n self.payload = payload\n \"\"\"The payload that was received by the bot when the action was triggered that this plugin method listens for\"\"\"\n self.triggered_action = triggered_action\n \"\"\"The action that triggered this plugin method\"\"\"\n self._webhook_client = AsyncWebhookClient(self.payload.response_url) if self.payload.response_url else None\n\n @property\n def user(self) -> User:\n \"\"\"The user that triggered the action\n\n Returns:\n the user that triggered the action\n \"\"\"\n return self._client.users[self.payload.user.id]\n\n @property\n def channel(self) -> Channel | None:\n \"\"\"The channel the action was triggered in\n\n Returns:\n the channel the action was triggered in or None if the action was triggered in a modal\n \"\"\"\n if self.payload.channel is None:\n return None\n return self._client.channels[self.payload.channel.id]\n\n @property\n def state(self) -> State | None:\n \"\"\"The state of the block when the action was triggered\n\n Returns:\n the state of the block when the action was triggered\n \"\"\"\n return self.payload.state\n\n @property\n def response_url(self) -> str | None:\n \"\"\"The response URL for the action\n\n Returns:\n the response URL for the action or `None` if the action was triggered in a modal\n \"\"\"\n return self.payload.response_url\n\n @property\n def trigger_id(self) -> str:\n \"\"\"The trigger id associated with the action\n\n The trigger id can be used to open a modal\n\n Note:\n The `trigger_id` is only valid for 3 seconds after the modal was submitted.\n\n You can use [`open_modal`][machine.plugins.block_action.BlockAction.open_modal] to open a modal instead of\n using the `trigger_id` directly.\n\n Returns:\n the trigger id for the action\n \"\"\"\n return self.payload.trigger_id\n\n async def say(\n self,\n text: str | None = None,\n attachments: Union[Sequence[Attachment], Sequence[dict[str, Any]], None] = None,\n blocks: Union[Sequence[Block], Sequence[dict[str, Any]], None] = None,\n ephemeral: bool = True,\n replace_original: bool = False,\n delete_original: bool = False,\n **kwargs: Any,\n ) -> WebhookResponse | None:\n \"\"\"Send a new message to the channel the block action was triggered in\n\n Send a new message to the channel the block action was triggered in, using the response_url as a webhook.\n If the block action happened in a modal, the response_url will be None and this method will not send a message\n but instead log a warning.\n Allows for rich formatting using [blocks] and/or [attachments]. You can provide blocks\n and attachments as Python dicts or you can use the [convenience classes] that the\n underlying slack client provides.\n This will send an ephemeral message by default, only visible to the user that triggered the action.\n You can set `ephemeral` to `False` to make the message visible to everyone in the channel.\n By default, Slack replaces the original message in which the action was triggered. This method overrides this\n behavior. If you want your message to replace the original, set replace_original to True.\n Any extra kwargs you provide, will be passed on directly to `AsyncWebhookClient.send()`\n\n [attachments]: https://api.slack.com/docs/message-attachments\n [blocks]: https://api.slack.com/reference/block-kit/blocks\n [convenience classes]: https://github.com/slackapi/python-slack-sdk/tree/main/slack/web/classes\n\n Args:\n text: message text\n attachments: optional attachments (see [attachments](https://api.slack.com/docs/message-attachments))\n blocks: optional blocks (see [blocks](https://api.slack.com/docs/message-attachments))\n ephemeral: `True/False` wether to send the message as an ephemeral message, only\n visible to the user that initiated the action\n replace_original: `True/False` whether the message that contains the block from which the action was\n triggered should be replaced by this message\n delete_original: `True/False` whether the message that contains the block from which the action was\n triggered should be deleted. No other parameters should be provided.\n\n Returns:\n Dictionary deserialized from `AsyncWebhookClient.send()`\n\n \"\"\"\n if self._webhook_client is None:\n logger.warning(\n \"response_url is None, cannot send message. This likely means the action was triggered in a modal.\"\n )\n return None\n\n response_type = \"ephemeral\" if ephemeral else \"in_channel\"\n return await self._webhook_client.send(\n text=text,\n attachments=attachments,\n blocks=blocks,\n response_type=response_type,\n replace_original=replace_original,\n delete_original=delete_original,\n **kwargs,\n )\n\n async def send_dm(\n self,\n text: str | None = None,\n attachments: Sequence[Attachment] | Sequence[dict[str, Any]] | None = None,\n blocks: Sequence[Block] | Sequence[dict[str, Any]] | None = None,\n **kwargs: Any,\n ) -> AsyncSlackResponse:\n \"\"\"Send a DM to the user that triggered the block action\n\n Send a Direct Message to the user that triggered the block action by opening a DM channel and\n sending a message to it.\n Allows for rich formatting using [blocks] and/or [attachments]. You can provide blocks\n and attachments as Python dicts or you can use the [convenience classes] that the\n underlying slack client provides.\n Any extra kwargs you provide, will be passed on directly to the `chat.postMessage` request.\n\n [attachments]: https://api.slack.com/docs/message-attachments\n [blocks]: https://api.slack.com/reference/block-kit/blocks\n [convenience classes]: https://github.com/slackapi/python-slack-sdk/tree/main/slack/web/classes\n\n Args:\n text: message text\n attachments: optional attachments (see [attachments](https://api.slack.com/docs/message-attachments))\n blocks: optional blocks (see [blocks](https://api.slack.com/reference/block-kit/blocks))\n\n Returns:\n Dictionary deserialized from [chat.postMessage](https://api.slack.com/methods/chat.postMessage) response.\n \"\"\"\n return await self._client.send_dm(self.user.id, text, attachments=attachments, blocks=blocks, **kwargs)\n\n async def open_modal(\n self,\n view: dict | View,\n **kwargs: Any,\n ) -> AsyncSlackResponse:\n \"\"\"Open a modal in response to the block action\n\n Open a modal in response to the block action, using the trigger_id that was returned when the block action was\n triggered.\n Any extra kwargs you provide, will be passed on directly to\n [views.open](https://api.slack.com/methods/views.open)\n\n Note:\n You have to call this method within 3 seconds of receiving the block action payload.\n\n Args:\n view: the view to open\n\n Returns:\n Dictionary deserialized from [views.open](https://api.slack.com/methods/views.open)\n \"\"\"\n return await self._client.open_modal(self.trigger_id, view, **kwargs)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 10056}, "tests/handlers/test_interactive_handler.py::14": {"resolved_imports": ["src/machine/handlers/interactive_handler.py", "src/machine/plugins/block_action.py", "src/machine/plugins/modals.py"], "used_names": ["_matches", "re"], "enclosing_function": "test_matches", "extracted_code": "# Source: src/machine/handlers/interactive_handler.py\ndef _matches(matcher: Union[re.Pattern[str], str, None], input_: str) -> bool:\n if matcher is None:\n return True\n if isinstance(matcher, re.Pattern):\n return matcher.match(input_) is not None\n return matcher == input_", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 294}, "tests/handlers/test_logging.py::14": {"resolved_imports": ["src/machine/handlers/logging.py"], "used_names": ["capture_logs", "gen_command_request", "log_request", "pytest"], "enclosing_function": "test_request_logger_handler", "extracted_code": "# Source: src/machine/handlers/logging.py\nasync def log_request(_: AsyncBaseSocketModeClient, request: SocketModeRequest) -> None:\n logger.debug(\n \"Request received\",\n type=request.type,\n request=request.to_dict(),\n accepts_response_payload=request.accepts_response_payload,\n )", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 311}, "tests/handlers/test_logging.py::13": {"resolved_imports": ["src/machine/handlers/logging.py"], "used_names": ["capture_logs", "gen_command_request", "log_request", "pytest"], "enclosing_function": "test_request_logger_handler", "extracted_code": "# Source: src/machine/handlers/logging.py\nasync def log_request(_: AsyncBaseSocketModeClient, request: SocketModeRequest) -> None:\n logger.debug(\n \"Request received\",\n type=request.type,\n request=request.to_dict(),\n accepts_response_payload=request.accepts_response_payload,\n )", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 311}, "tests/handlers/test_logging.py::15": {"resolved_imports": ["src/machine/handlers/logging.py"], "used_names": ["capture_logs", "gen_command_request", "log_request", "pytest"], "enclosing_function": "test_request_logger_handler", "extracted_code": "# Source: src/machine/handlers/logging.py\nasync def log_request(_: AsyncBaseSocketModeClient, request: SocketModeRequest) -> None:\n logger.debug(\n \"Request received\",\n type=request.type,\n request=request.to_dict(),\n accepts_response_payload=request.accepts_response_payload,\n )", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 311}, "tests/handlers/test_message_handler.py::83": {"resolved_imports": ["src/machine/handlers/message_handler.py", "src/machine/plugins/message.py"], "used_names": ["Message"], "enclosing_function": "_assert_message", "extracted_code": "# Source: src/machine/plugins/message.py\nclass Message:\n \"\"\"A message that was received by the bot\n\n This class represents a message that was received by the bot and passed to one or more\n plugins. It contains the message (text) itself, and metadata about the message, such as the\n sender of the message, the channel the message was sent to.\n\n The `Message` class also contains convenience methods for replying to the message in the\n right channel, replying to the sender, etc.\n \"\"\"\n\n # TODO: create proper class for msg_event\n def __init__(self, client: SlackClient, msg_event: dict[str, Any]):\n self._client = client\n self._msg_event = msg_event\n\n @property\n def sender(self) -> User:\n \"\"\"The sender of the message\n\n Returns:\n the User the message was sent by\n \"\"\"\n return self._client.users[self._msg_event[\"user\"]]\n\n @property\n def channel(self) -> Channel:\n \"\"\"The channel the message was sent to\n\n Returns:\n the Channel the message was sent to\n \"\"\"\n return self._client.channels[self._msg_event[\"channel\"]]\n\n @property\n def is_dm(self) -> bool:\n \"\"\"Is the message a direct message\n\n Returns:\n `True` if the message was _not_ sent in a channel or group, `False` otherwise\n \"\"\"\n channel_id = self._msg_event[\"channel\"]\n return not (channel_id.startswith(\"C\") or channel_id.startswith(\"G\"))\n\n @property\n def text(self) -> str:\n \"\"\"The body of the actual message\n\n Returns:\n the body (text) of the actual message\n \"\"\"\n return self._msg_event[\"text\"]\n\n @property\n def at_sender(self) -> str:\n \"\"\"The sender of the message formatted as mention\n\n Returns:\n a string representation of the sender of the message, formatted as\n [mention](https://api.slack.com/docs/message-formatting#linking_to_channels_and_users),\n to be used in messages\n \"\"\"\n return self.sender.fmt_mention()\n\n @property\n def ts(self) -> str:\n \"\"\"The timestamp of the message\n\n Returns:\n the timestamp of the message\n \"\"\"\n return self._msg_event[\"ts\"]\n\n @property\n def in_thread(self) -> bool:\n \"\"\"Is message in a thread\n\n Returns:\n the message is in a thread\n \"\"\"\n return \"thread_ts\" in self._msg_event\n\n async def say(\n self,\n text: str | None = None,\n attachments: Sequence[Attachment] | Sequence[dict[str, Any]] | None = None,\n blocks: Sequence[Block] | Sequence[dict[str, Any]] | None = None,\n thread_ts: str | None = None,\n ephemeral: bool = False,\n **kwargs: Any,\n ) -> AsyncSlackResponse:\n \"\"\"Send a new message to the channel the original message was received in\n\n Send a new message to the channel the original message was received in, using the WebAPI.\n Allows for rich formatting using [blocks] and/or [attachments]. You can provide blocks\n and attachments as Python dicts or you can use the [convenience classes] that the\n underlying slack client provides.\n Can also reply to a thread and send an ephemeral message only visible to the sender of the\n original message. Ephemeral messages and threaded messages are mutually exclusive, and\n `ephemeral` takes precedence over `thread_ts`\n Any extra kwargs you provide, will be passed on directly to the [chat.postMessage] or\n [chat.postEphemeral] request.\n\n [attachments]: https://api.slack.com/docs/message-attachments\n [blocks]: https://api.slack.com/reference/block-kit/blocks\n [convenience classes]:\n https://github.com/slackapi/python-slackclient/tree/master/slack/web/classes\n [chat.postMessage]: https://api.slack.com/methods/chat.postMessage\n [chat.postEphemeral]: https://api.slack.com/methods/chat.postEphemeral\n\n Args:\n text: message text\n attachments: optional attachments (see [attachments](https://api.slack.com/docs/message-attachments))\n blocks: optional blocks (see [blocks](https://api.slack.com/reference/block-kit/blocks))\n thread_ts: optional timestamp of thread, to send a message in that thread\n ephemeral: `True/False` wether to send the message as an ephemeral message, only\n visible to the sender of the original message\n\n Returns:\n Dictionary deserialized from [chat.postMessage](https://api.slack.com/methods/chat.postMessage) response,\n or [chat.postEphemeral](https://api.slack.com/methods/chat.postEphemeral) if `ephemeral` is True.\n\n\n \"\"\"\n ephemeral_user = self.sender.id if ephemeral else None\n\n return await self._client.send(\n self.channel.id,\n text=text,\n attachments=attachments,\n blocks=blocks,\n thread_ts=thread_ts,\n ephemeral_user=ephemeral_user,\n **kwargs,\n )\n\n async def say_scheduled(\n self,\n when: datetime,\n text: str,\n attachments: Sequence[Attachment] | Sequence[dict[str, Any]] | None = None,\n blocks: Sequence[Block] | Sequence[dict[str, Any]] | None = None,\n thread_ts: str | None = None,\n **kwargs: Any,\n ) -> AsyncSlackResponse:\n \"\"\"Schedule a message\n\n This is the scheduled version of [`say()`][machine.plugins.message.Message.say].\n It behaves the same, but will send the message at the scheduled time.\n\n Args:\n when: when you want the message to be sent, as [`datetime`][datetime.datetime] instance\n text: message text\n attachments: optional attachments (see [attachments](https://api.slack.com/docs/message-attachments))\n blocks: optional blocks (see [blocks](https://api.slack.com/reference/block-kit/blocks))\n thread_ts: optional timestamp of thread, to send a message in that thread\n\n Returns:\n Dictionary deserialized from [chat.scheduleMessage](https://api.slack.com/methods/chat.scheduleMessage)\n response.\n \"\"\"\n return await self._client.send_scheduled(\n when,\n self.channel.id,\n text=text,\n attachments=attachments,\n blocks=blocks,\n thread_ts=thread_ts,\n **kwargs,\n )\n\n async def reply(\n self,\n text: str | None = None,\n attachments: Sequence[Attachment] | Sequence[dict[str, Any]] | None = None,\n blocks: Sequence[Block] | Sequence[dict[str, Any]] | None = None,\n in_thread: bool = False,\n ephemeral: bool = False,\n **kwargs: Any,\n ) -> AsyncSlackResponse:\n \"\"\"Reply to the sender of the original message\n\n Reply to the sender of the original message with a new message, mentioning that user. Rich\n formatting using [blocks] and/or [attachments] is possible. You can provide blocks\n and attachments as Python dicts or you can use the [convenience classes] that the\n underlying slack client provides.\n Can also reply to a thread and send an ephemeral message only visible to the sender of the\n original message. In the case of in-thread response, the sender of the original message\n will not be mentioned. Ephemeral messages and threaded messages are mutually exclusive,\n and `ephemeral` takes precedence over `in_thread`\n Any extra kwargs you provide, will be passed on directly to the [chat.postMessage] or\n [chat.postEphemeral] request.\n\n [attachments]: https://api.slack.com/docs/message-attachments\n [blocks]: https://api.slack.com/reference/block-kit/blocks\n [convenience classes]:\n https://github.com/slackapi/python-slackclient/tree/master/slack/web/classes\n [chat.postMessage]: https://api.slack.com/methods/chat.postMessage\n [chat.postEphemeral]: https://api.slack.com/methods/chat.postEphemeral\n\n Args:\n text: message text\n attachments: optional attachments (see [attachments](https://api.slack.com/docs/message-attachments))\n blocks: optional blocks (see [blocks](https://api.slack.com/reference/block-kit/blocks)\n in_thread: `True/False` wether to reply to the original message in-thread\n ephemeral: `True/False` wether to send the message as an ephemeral message, only\n visible to the sender of the original message\n\n Returns:\n Dictionary deserialized from [chat.postMessage](https://api.slack.com/methods/chat.postMessage) response,\n or [chat.postEphemeral](https://api.slack.com/methods/chat.postEphemeral) if `ephemeral` is True.\n \"\"\"\n if in_thread and not ephemeral:\n return await self.say(text, attachments=attachments, blocks=blocks, thread_ts=self.ts, **kwargs)\n else:\n text = self._create_reply(text)\n return await self.say(text, attachments=attachments, blocks=blocks, ephemeral=ephemeral, **kwargs)\n\n async def reply_scheduled(\n self,\n when: datetime,\n text: str,\n attachments: Sequence[Attachment] | Sequence[dict[str, Any]] | None = None,\n blocks: Sequence[Block] | Sequence[dict[str, Any]] | None = None,\n in_thread: bool = False,\n **kwargs: Any,\n ) -> AsyncSlackResponse:\n \"\"\"Schedule a reply and send it\n\n This is the scheduled version of [`reply()`][machine.plugins.message.Message.reply].\n It behaves the same, but will send the reply at the scheduled time.\n\n Args:\n when: when you want the message to be sent, as :py:class:`datetime.datetime` instance\n text: message text\n attachments: optional attachments (see [attachments](https://api.slack.com/docs/message-attachments))\n blocks: optional blocks (see [blocks](https://api.slack.com/reference/block-kit/blocks))\n in_thread: `True/False` wether to reply to the original message in-thread\n\n Returns:\n Dictionary deserialized from [chat.scheduleMessage](https://api.slack.com/methods/chat.scheduleMessage)\n response.\n \"\"\"\n if in_thread:\n return await self.say_scheduled(\n when, text, attachments=attachments, blocks=blocks, thread_ts=self.ts, **kwargs\n )\n else:\n text = cast(str, self._create_reply(text))\n return await self.say_scheduled(when, text, attachments=attachments, blocks=blocks, **kwargs)\n\n async def reply_dm(\n self,\n text: str | None = None,\n attachments: Sequence[Attachment] | Sequence[dict[str, Any]] | None = None,\n blocks: Sequence[Block] | Sequence[dict[str, Any]] | None = None,\n **kwargs: Any,\n ) -> AsyncSlackResponse:\n \"\"\"Reply to the sender of the original message with a DM\n\n Reply in a Direct Message to the sender of the original message by opening a DM channel and\n sending a message to it. Allows for rich formatting using [blocks] and/or [attachments].\n You can provide blocks and attachments as Python dicts or you can use the\n [convenience classes] that the underlying slack client provides.\n Any extra kwargs you provide, will be passed on directly to the [chat.postMessage] request.\n\n [attachments]: https://api.slack.com/docs/message-attachments\n [blocks]: https://api.slack.com/reference/block-kit/blocks\n [convenience classes]:\n https://github.com/slackapi/python-slackclient/tree/master/slack/web/classes\n [chat.postMessage]: https://api.slack.com/methods/chat.postMessage\n\n Args:\n text: message text\n attachments: optional attachments (see [attachments](https://api.slack.com/docs/message-attachments))\n blocks: optional blocks (see [blocks](https://api.slack.com/reference/block-kit/blocks))\n\n Returns:\n Dictionary deserialized from [chat.postMessage](https://api.slack.com/methods/chat.postMessage) response.\n \"\"\"\n return await self._client.send_dm(self.sender.id, text, attachments=attachments, blocks=blocks, **kwargs)\n\n async def reply_dm_scheduled(\n self,\n when: datetime,\n text: str,\n attachments: Sequence[Attachment] | Sequence[dict[str, Any]] | None = None,\n blocks: Sequence[Block] | Sequence[dict[str, Any]] | None = None,\n **kwargs: Any,\n ) -> AsyncSlackResponse:\n \"\"\"Schedule a DM reply and send it\n\n This is the scheduled version of [`reply_dm()`][machine.plugins.message.Message.reply_dm].\n It behaves the same, but will send the DM at the scheduled time.\n\n Args:\n when: when you want the message to be sent, as :py:class:`datetime.datetime` instance\n text: message text\n attachments: optional attachments (see [attachments](https://api.slack.com/docs/message-attachments))\n blocks: optional blocks (see [blocks](https://api.slack.com/reference/block-kit/blocks))\n\n Returns:\n Dictionary deserialized from [chat.scheduleMessage](https://api.slack.com/methods/chat.scheduleMessage)\n response.\n \"\"\"\n return await self._client.send_dm_scheduled(\n when, self.sender.id, text=text, attachments=attachments, blocks=blocks, **kwargs\n )\n\n async def react(self, emoji: str) -> AsyncSlackResponse:\n \"\"\"React to the original message\n\n Add a reaction to the original message\n\n Args:\n emoji: what emoji to react with (should be a string, like 'angel', 'thumbsup', etc.)\n\n Returns:\n Dictionary deserialized from [reactions.add](https://api.slack.com/methods/reactions.add) response.\n \"\"\"\n return await self._client.react(self.channel.id, self._msg_event[\"ts\"], emoji)\n\n def _create_reply(self, text: str | None) -> str | None:\n if not self.is_dm and text is not None:\n return f\"{self.at_sender}: {text}\"\n else:\n return text\n\n async def pin_message(self) -> AsyncSlackResponse:\n \"\"\"Pin message\n\n Pin the current message in the channel it was posted in\n\n Returns:\n Dictionary deserialized from [pins.add](https://api.slack.com/methods/pins.add) response.\n \"\"\"\n return await self._client.pin_message(self.channel, self.ts)\n\n def __str__(self) -> str:\n if self.channel.is_im:\n message = f\"Message '{self.text}', sent by user @{self.sender.profile.real_name} in DM\"\n else:\n message = (\n f\"Message '{self.text}', sent by user @{self.sender.profile.real_name} in channel #{self.channel.name}\"\n )\n return message\n\n def __repr__(self) -> str:\n return f\"Message(text={self.text!r}, sender={self.sender.profile.real_name!r}, channel={self.channel.name!r})\"", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 15115}, "tests/handlers/test_message_handler.py::84": {"resolved_imports": ["src/machine/handlers/message_handler.py", "src/machine/plugins/message.py"], "used_names": ["Message"], "enclosing_function": "_assert_message", "extracted_code": "# Source: src/machine/plugins/message.py\nclass Message:\n \"\"\"A message that was received by the bot\n\n This class represents a message that was received by the bot and passed to one or more\n plugins. It contains the message (text) itself, and metadata about the message, such as the\n sender of the message, the channel the message was sent to.\n\n The `Message` class also contains convenience methods for replying to the message in the\n right channel, replying to the sender, etc.\n \"\"\"\n\n # TODO: create proper class for msg_event\n def __init__(self, client: SlackClient, msg_event: dict[str, Any]):\n self._client = client\n self._msg_event = msg_event\n\n @property\n def sender(self) -> User:\n \"\"\"The sender of the message\n\n Returns:\n the User the message was sent by\n \"\"\"\n return self._client.users[self._msg_event[\"user\"]]\n\n @property\n def channel(self) -> Channel:\n \"\"\"The channel the message was sent to\n\n Returns:\n the Channel the message was sent to\n \"\"\"\n return self._client.channels[self._msg_event[\"channel\"]]\n\n @property\n def is_dm(self) -> bool:\n \"\"\"Is the message a direct message\n\n Returns:\n `True` if the message was _not_ sent in a channel or group, `False` otherwise\n \"\"\"\n channel_id = self._msg_event[\"channel\"]\n return not (channel_id.startswith(\"C\") or channel_id.startswith(\"G\"))\n\n @property\n def text(self) -> str:\n \"\"\"The body of the actual message\n\n Returns:\n the body (text) of the actual message\n \"\"\"\n return self._msg_event[\"text\"]\n\n @property\n def at_sender(self) -> str:\n \"\"\"The sender of the message formatted as mention\n\n Returns:\n a string representation of the sender of the message, formatted as\n [mention](https://api.slack.com/docs/message-formatting#linking_to_channels_and_users),\n to be used in messages\n \"\"\"\n return self.sender.fmt_mention()\n\n @property\n def ts(self) -> str:\n \"\"\"The timestamp of the message\n\n Returns:\n the timestamp of the message\n \"\"\"\n return self._msg_event[\"ts\"]\n\n @property\n def in_thread(self) -> bool:\n \"\"\"Is message in a thread\n\n Returns:\n the message is in a thread\n \"\"\"\n return \"thread_ts\" in self._msg_event\n\n async def say(\n self,\n text: str | None = None,\n attachments: Sequence[Attachment] | Sequence[dict[str, Any]] | None = None,\n blocks: Sequence[Block] | Sequence[dict[str, Any]] | None = None,\n thread_ts: str | None = None,\n ephemeral: bool = False,\n **kwargs: Any,\n ) -> AsyncSlackResponse:\n \"\"\"Send a new message to the channel the original message was received in\n\n Send a new message to the channel the original message was received in, using the WebAPI.\n Allows for rich formatting using [blocks] and/or [attachments]. You can provide blocks\n and attachments as Python dicts or you can use the [convenience classes] that the\n underlying slack client provides.\n Can also reply to a thread and send an ephemeral message only visible to the sender of the\n original message. Ephemeral messages and threaded messages are mutually exclusive, and\n `ephemeral` takes precedence over `thread_ts`\n Any extra kwargs you provide, will be passed on directly to the [chat.postMessage] or\n [chat.postEphemeral] request.\n\n [attachments]: https://api.slack.com/docs/message-attachments\n [blocks]: https://api.slack.com/reference/block-kit/blocks\n [convenience classes]:\n https://github.com/slackapi/python-slackclient/tree/master/slack/web/classes\n [chat.postMessage]: https://api.slack.com/methods/chat.postMessage\n [chat.postEphemeral]: https://api.slack.com/methods/chat.postEphemeral\n\n Args:\n text: message text\n attachments: optional attachments (see [attachments](https://api.slack.com/docs/message-attachments))\n blocks: optional blocks (see [blocks](https://api.slack.com/reference/block-kit/blocks))\n thread_ts: optional timestamp of thread, to send a message in that thread\n ephemeral: `True/False` wether to send the message as an ephemeral message, only\n visible to the sender of the original message\n\n Returns:\n Dictionary deserialized from [chat.postMessage](https://api.slack.com/methods/chat.postMessage) response,\n or [chat.postEphemeral](https://api.slack.com/methods/chat.postEphemeral) if `ephemeral` is True.\n\n\n \"\"\"\n ephemeral_user = self.sender.id if ephemeral else None\n\n return await self._client.send(\n self.channel.id,\n text=text,\n attachments=attachments,\n blocks=blocks,\n thread_ts=thread_ts,\n ephemeral_user=ephemeral_user,\n **kwargs,\n )\n\n async def say_scheduled(\n self,\n when: datetime,\n text: str,\n attachments: Sequence[Attachment] | Sequence[dict[str, Any]] | None = None,\n blocks: Sequence[Block] | Sequence[dict[str, Any]] | None = None,\n thread_ts: str | None = None,\n **kwargs: Any,\n ) -> AsyncSlackResponse:\n \"\"\"Schedule a message\n\n This is the scheduled version of [`say()`][machine.plugins.message.Message.say].\n It behaves the same, but will send the message at the scheduled time.\n\n Args:\n when: when you want the message to be sent, as [`datetime`][datetime.datetime] instance\n text: message text\n attachments: optional attachments (see [attachments](https://api.slack.com/docs/message-attachments))\n blocks: optional blocks (see [blocks](https://api.slack.com/reference/block-kit/blocks))\n thread_ts: optional timestamp of thread, to send a message in that thread\n\n Returns:\n Dictionary deserialized from [chat.scheduleMessage](https://api.slack.com/methods/chat.scheduleMessage)\n response.\n \"\"\"\n return await self._client.send_scheduled(\n when,\n self.channel.id,\n text=text,\n attachments=attachments,\n blocks=blocks,\n thread_ts=thread_ts,\n **kwargs,\n )\n\n async def reply(\n self,\n text: str | None = None,\n attachments: Sequence[Attachment] | Sequence[dict[str, Any]] | None = None,\n blocks: Sequence[Block] | Sequence[dict[str, Any]] | None = None,\n in_thread: bool = False,\n ephemeral: bool = False,\n **kwargs: Any,\n ) -> AsyncSlackResponse:\n \"\"\"Reply to the sender of the original message\n\n Reply to the sender of the original message with a new message, mentioning that user. Rich\n formatting using [blocks] and/or [attachments] is possible. You can provide blocks\n and attachments as Python dicts or you can use the [convenience classes] that the\n underlying slack client provides.\n Can also reply to a thread and send an ephemeral message only visible to the sender of the\n original message. In the case of in-thread response, the sender of the original message\n will not be mentioned. Ephemeral messages and threaded messages are mutually exclusive,\n and `ephemeral` takes precedence over `in_thread`\n Any extra kwargs you provide, will be passed on directly to the [chat.postMessage] or\n [chat.postEphemeral] request.\n\n [attachments]: https://api.slack.com/docs/message-attachments\n [blocks]: https://api.slack.com/reference/block-kit/blocks\n [convenience classes]:\n https://github.com/slackapi/python-slackclient/tree/master/slack/web/classes\n [chat.postMessage]: https://api.slack.com/methods/chat.postMessage\n [chat.postEphemeral]: https://api.slack.com/methods/chat.postEphemeral\n\n Args:\n text: message text\n attachments: optional attachments (see [attachments](https://api.slack.com/docs/message-attachments))\n blocks: optional blocks (see [blocks](https://api.slack.com/reference/block-kit/blocks)\n in_thread: `True/False` wether to reply to the original message in-thread\n ephemeral: `True/False` wether to send the message as an ephemeral message, only\n visible to the sender of the original message\n\n Returns:\n Dictionary deserialized from [chat.postMessage](https://api.slack.com/methods/chat.postMessage) response,\n or [chat.postEphemeral](https://api.slack.com/methods/chat.postEphemeral) if `ephemeral` is True.\n \"\"\"\n if in_thread and not ephemeral:\n return await self.say(text, attachments=attachments, blocks=blocks, thread_ts=self.ts, **kwargs)\n else:\n text = self._create_reply(text)\n return await self.say(text, attachments=attachments, blocks=blocks, ephemeral=ephemeral, **kwargs)\n\n async def reply_scheduled(\n self,\n when: datetime,\n text: str,\n attachments: Sequence[Attachment] | Sequence[dict[str, Any]] | None = None,\n blocks: Sequence[Block] | Sequence[dict[str, Any]] | None = None,\n in_thread: bool = False,\n **kwargs: Any,\n ) -> AsyncSlackResponse:\n \"\"\"Schedule a reply and send it\n\n This is the scheduled version of [`reply()`][machine.plugins.message.Message.reply].\n It behaves the same, but will send the reply at the scheduled time.\n\n Args:\n when: when you want the message to be sent, as :py:class:`datetime.datetime` instance\n text: message text\n attachments: optional attachments (see [attachments](https://api.slack.com/docs/message-attachments))\n blocks: optional blocks (see [blocks](https://api.slack.com/reference/block-kit/blocks))\n in_thread: `True/False` wether to reply to the original message in-thread\n\n Returns:\n Dictionary deserialized from [chat.scheduleMessage](https://api.slack.com/methods/chat.scheduleMessage)\n response.\n \"\"\"\n if in_thread:\n return await self.say_scheduled(\n when, text, attachments=attachments, blocks=blocks, thread_ts=self.ts, **kwargs\n )\n else:\n text = cast(str, self._create_reply(text))\n return await self.say_scheduled(when, text, attachments=attachments, blocks=blocks, **kwargs)\n\n async def reply_dm(\n self,\n text: str | None = None,\n attachments: Sequence[Attachment] | Sequence[dict[str, Any]] | None = None,\n blocks: Sequence[Block] | Sequence[dict[str, Any]] | None = None,\n **kwargs: Any,\n ) -> AsyncSlackResponse:\n \"\"\"Reply to the sender of the original message with a DM\n\n Reply in a Direct Message to the sender of the original message by opening a DM channel and\n sending a message to it. Allows for rich formatting using [blocks] and/or [attachments].\n You can provide blocks and attachments as Python dicts or you can use the\n [convenience classes] that the underlying slack client provides.\n Any extra kwargs you provide, will be passed on directly to the [chat.postMessage] request.\n\n [attachments]: https://api.slack.com/docs/message-attachments\n [blocks]: https://api.slack.com/reference/block-kit/blocks\n [convenience classes]:\n https://github.com/slackapi/python-slackclient/tree/master/slack/web/classes\n [chat.postMessage]: https://api.slack.com/methods/chat.postMessage\n\n Args:\n text: message text\n attachments: optional attachments (see [attachments](https://api.slack.com/docs/message-attachments))\n blocks: optional blocks (see [blocks](https://api.slack.com/reference/block-kit/blocks))\n\n Returns:\n Dictionary deserialized from [chat.postMessage](https://api.slack.com/methods/chat.postMessage) response.\n \"\"\"\n return await self._client.send_dm(self.sender.id, text, attachments=attachments, blocks=blocks, **kwargs)\n\n async def reply_dm_scheduled(\n self,\n when: datetime,\n text: str,\n attachments: Sequence[Attachment] | Sequence[dict[str, Any]] | None = None,\n blocks: Sequence[Block] | Sequence[dict[str, Any]] | None = None,\n **kwargs: Any,\n ) -> AsyncSlackResponse:\n \"\"\"Schedule a DM reply and send it\n\n This is the scheduled version of [`reply_dm()`][machine.plugins.message.Message.reply_dm].\n It behaves the same, but will send the DM at the scheduled time.\n\n Args:\n when: when you want the message to be sent, as :py:class:`datetime.datetime` instance\n text: message text\n attachments: optional attachments (see [attachments](https://api.slack.com/docs/message-attachments))\n blocks: optional blocks (see [blocks](https://api.slack.com/reference/block-kit/blocks))\n\n Returns:\n Dictionary deserialized from [chat.scheduleMessage](https://api.slack.com/methods/chat.scheduleMessage)\n response.\n \"\"\"\n return await self._client.send_dm_scheduled(\n when, self.sender.id, text=text, attachments=attachments, blocks=blocks, **kwargs\n )\n\n async def react(self, emoji: str) -> AsyncSlackResponse:\n \"\"\"React to the original message\n\n Add a reaction to the original message\n\n Args:\n emoji: what emoji to react with (should be a string, like 'angel', 'thumbsup', etc.)\n\n Returns:\n Dictionary deserialized from [reactions.add](https://api.slack.com/methods/reactions.add) response.\n \"\"\"\n return await self._client.react(self.channel.id, self._msg_event[\"ts\"], emoji)\n\n def _create_reply(self, text: str | None) -> str | None:\n if not self.is_dm and text is not None:\n return f\"{self.at_sender}: {text}\"\n else:\n return text\n\n async def pin_message(self) -> AsyncSlackResponse:\n \"\"\"Pin message\n\n Pin the current message in the channel it was posted in\n\n Returns:\n Dictionary deserialized from [pins.add](https://api.slack.com/methods/pins.add) response.\n \"\"\"\n return await self._client.pin_message(self.channel, self.ts)\n\n def __str__(self) -> str:\n if self.channel.is_im:\n message = f\"Message '{self.text}', sent by user @{self.sender.profile.real_name} in DM\"\n else:\n message = (\n f\"Message '{self.text}', sent by user @{self.sender.profile.real_name} in channel #{self.channel.name}\"\n )\n return message\n\n def __repr__(self) -> str:\n return f\"Message(text={self.text!r}, sender={self.sender.profile.real_name!r}, channel={self.channel.name!r})\"", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 15115}, "tests/handlers/test_message_handler.py::42": {"resolved_imports": ["src/machine/handlers/message_handler.py", "src/machine/plugins/message.py"], "used_names": ["_check_bot_mention", "generate_message_matcher"], "enclosing_function": "test_check_bot_mention", "extracted_code": "# Source: src/machine/handlers/message_handler.py\ndef generate_message_matcher(settings: Mapping) -> re.Pattern[str]:\n alias_regex = \"\"\n if \"ALIASES\" in settings:\n logger.debug(\"Setting aliases to %s\", settings[\"ALIASES\"])\n alias_alternatives = \"|\".join([re.escape(alias) for alias in settings[\"ALIASES\"].split(\",\")])\n alias_regex = f\"|(?P<alias>{alias_alternatives})\"\n return re.compile(\n rf\"^(?:<@(?P<atuser>\\w+)>:?|(?P<username>\\w+):{alias_regex}) ?(?P<text>.*)$\",\n re.DOTALL,\n )\n\ndef _check_bot_mention(\n event: dict[str, Any], bot_name: str, bot_id: str, message_matcher: re.Pattern[str]\n) -> dict[str, Any] | None:\n full_text = event.get(\"text\", \"\")\n channel_type = event[\"channel_type\"]\n m = message_matcher.match(full_text)\n\n if channel_type == \"channel\" or channel_type == \"group\":\n if not m:\n return None\n\n matches = m.groupdict()\n\n atuser = matches.get(\"atuser\")\n username = matches.get(\"username\")\n text = matches.get(\"text\")\n alias = matches.get(\"alias\")\n\n if alias:\n atuser = bot_id\n\n if atuser != bot_id and username != bot_name:\n # a channel message at other user\n return None\n\n event[\"text\"] = text\n else:\n if m:\n event[\"text\"] = m.groupdict().get(\"text\", None)\n return event", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 1385}, "tests/handlers/test_message_handler.py::88": {"resolved_imports": ["src/machine/handlers/message_handler.py", "src/machine/plugins/message.py"], "used_names": ["Message"], "enclosing_function": "_assert_message", "extracted_code": "# Source: src/machine/plugins/message.py\nclass Message:\n \"\"\"A message that was received by the bot\n\n This class represents a message that was received by the bot and passed to one or more\n plugins. It contains the message (text) itself, and metadata about the message, such as the\n sender of the message, the channel the message was sent to.\n\n The `Message` class also contains convenience methods for replying to the message in the\n right channel, replying to the sender, etc.\n \"\"\"\n\n # TODO: create proper class for msg_event\n def __init__(self, client: SlackClient, msg_event: dict[str, Any]):\n self._client = client\n self._msg_event = msg_event\n\n @property\n def sender(self) -> User:\n \"\"\"The sender of the message\n\n Returns:\n the User the message was sent by\n \"\"\"\n return self._client.users[self._msg_event[\"user\"]]\n\n @property\n def channel(self) -> Channel:\n \"\"\"The channel the message was sent to\n\n Returns:\n the Channel the message was sent to\n \"\"\"\n return self._client.channels[self._msg_event[\"channel\"]]\n\n @property\n def is_dm(self) -> bool:\n \"\"\"Is the message a direct message\n\n Returns:\n `True` if the message was _not_ sent in a channel or group, `False` otherwise\n \"\"\"\n channel_id = self._msg_event[\"channel\"]\n return not (channel_id.startswith(\"C\") or channel_id.startswith(\"G\"))\n\n @property\n def text(self) -> str:\n \"\"\"The body of the actual message\n\n Returns:\n the body (text) of the actual message\n \"\"\"\n return self._msg_event[\"text\"]\n\n @property\n def at_sender(self) -> str:\n \"\"\"The sender of the message formatted as mention\n\n Returns:\n a string representation of the sender of the message, formatted as\n [mention](https://api.slack.com/docs/message-formatting#linking_to_channels_and_users),\n to be used in messages\n \"\"\"\n return self.sender.fmt_mention()\n\n @property\n def ts(self) -> str:\n \"\"\"The timestamp of the message\n\n Returns:\n the timestamp of the message\n \"\"\"\n return self._msg_event[\"ts\"]\n\n @property\n def in_thread(self) -> bool:\n \"\"\"Is message in a thread\n\n Returns:\n the message is in a thread\n \"\"\"\n return \"thread_ts\" in self._msg_event\n\n async def say(\n self,\n text: str | None = None,\n attachments: Sequence[Attachment] | Sequence[dict[str, Any]] | None = None,\n blocks: Sequence[Block] | Sequence[dict[str, Any]] | None = None,\n thread_ts: str | None = None,\n ephemeral: bool = False,\n **kwargs: Any,\n ) -> AsyncSlackResponse:\n \"\"\"Send a new message to the channel the original message was received in\n\n Send a new message to the channel the original message was received in, using the WebAPI.\n Allows for rich formatting using [blocks] and/or [attachments]. You can provide blocks\n and attachments as Python dicts or you can use the [convenience classes] that the\n underlying slack client provides.\n Can also reply to a thread and send an ephemeral message only visible to the sender of the\n original message. Ephemeral messages and threaded messages are mutually exclusive, and\n `ephemeral` takes precedence over `thread_ts`\n Any extra kwargs you provide, will be passed on directly to the [chat.postMessage] or\n [chat.postEphemeral] request.\n\n [attachments]: https://api.slack.com/docs/message-attachments\n [blocks]: https://api.slack.com/reference/block-kit/blocks\n [convenience classes]:\n https://github.com/slackapi/python-slackclient/tree/master/slack/web/classes\n [chat.postMessage]: https://api.slack.com/methods/chat.postMessage\n [chat.postEphemeral]: https://api.slack.com/methods/chat.postEphemeral\n\n Args:\n text: message text\n attachments: optional attachments (see [attachments](https://api.slack.com/docs/message-attachments))\n blocks: optional blocks (see [blocks](https://api.slack.com/reference/block-kit/blocks))\n thread_ts: optional timestamp of thread, to send a message in that thread\n ephemeral: `True/False` wether to send the message as an ephemeral message, only\n visible to the sender of the original message\n\n Returns:\n Dictionary deserialized from [chat.postMessage](https://api.slack.com/methods/chat.postMessage) response,\n or [chat.postEphemeral](https://api.slack.com/methods/chat.postEphemeral) if `ephemeral` is True.\n\n\n \"\"\"\n ephemeral_user = self.sender.id if ephemeral else None\n\n return await self._client.send(\n self.channel.id,\n text=text,\n attachments=attachments,\n blocks=blocks,\n thread_ts=thread_ts,\n ephemeral_user=ephemeral_user,\n **kwargs,\n )\n\n async def say_scheduled(\n self,\n when: datetime,\n text: str,\n attachments: Sequence[Attachment] | Sequence[dict[str, Any]] | None = None,\n blocks: Sequence[Block] | Sequence[dict[str, Any]] | None = None,\n thread_ts: str | None = None,\n **kwargs: Any,\n ) -> AsyncSlackResponse:\n \"\"\"Schedule a message\n\n This is the scheduled version of [`say()`][machine.plugins.message.Message.say].\n It behaves the same, but will send the message at the scheduled time.\n\n Args:\n when: when you want the message to be sent, as [`datetime`][datetime.datetime] instance\n text: message text\n attachments: optional attachments (see [attachments](https://api.slack.com/docs/message-attachments))\n blocks: optional blocks (see [blocks](https://api.slack.com/reference/block-kit/blocks))\n thread_ts: optional timestamp of thread, to send a message in that thread\n\n Returns:\n Dictionary deserialized from [chat.scheduleMessage](https://api.slack.com/methods/chat.scheduleMessage)\n response.\n \"\"\"\n return await self._client.send_scheduled(\n when,\n self.channel.id,\n text=text,\n attachments=attachments,\n blocks=blocks,\n thread_ts=thread_ts,\n **kwargs,\n )\n\n async def reply(\n self,\n text: str | None = None,\n attachments: Sequence[Attachment] | Sequence[dict[str, Any]] | None = None,\n blocks: Sequence[Block] | Sequence[dict[str, Any]] | None = None,\n in_thread: bool = False,\n ephemeral: bool = False,\n **kwargs: Any,\n ) -> AsyncSlackResponse:\n \"\"\"Reply to the sender of the original message\n\n Reply to the sender of the original message with a new message, mentioning that user. Rich\n formatting using [blocks] and/or [attachments] is possible. You can provide blocks\n and attachments as Python dicts or you can use the [convenience classes] that the\n underlying slack client provides.\n Can also reply to a thread and send an ephemeral message only visible to the sender of the\n original message. In the case of in-thread response, the sender of the original message\n will not be mentioned. Ephemeral messages and threaded messages are mutually exclusive,\n and `ephemeral` takes precedence over `in_thread`\n Any extra kwargs you provide, will be passed on directly to the [chat.postMessage] or\n [chat.postEphemeral] request.\n\n [attachments]: https://api.slack.com/docs/message-attachments\n [blocks]: https://api.slack.com/reference/block-kit/blocks\n [convenience classes]:\n https://github.com/slackapi/python-slackclient/tree/master/slack/web/classes\n [chat.postMessage]: https://api.slack.com/methods/chat.postMessage\n [chat.postEphemeral]: https://api.slack.com/methods/chat.postEphemeral\n\n Args:\n text: message text\n attachments: optional attachments (see [attachments](https://api.slack.com/docs/message-attachments))\n blocks: optional blocks (see [blocks](https://api.slack.com/reference/block-kit/blocks)\n in_thread: `True/False` wether to reply to the original message in-thread\n ephemeral: `True/False` wether to send the message as an ephemeral message, only\n visible to the sender of the original message\n\n Returns:\n Dictionary deserialized from [chat.postMessage](https://api.slack.com/methods/chat.postMessage) response,\n or [chat.postEphemeral](https://api.slack.com/methods/chat.postEphemeral) if `ephemeral` is True.\n \"\"\"\n if in_thread and not ephemeral:\n return await self.say(text, attachments=attachments, blocks=blocks, thread_ts=self.ts, **kwargs)\n else:\n text = self._create_reply(text)\n return await self.say(text, attachments=attachments, blocks=blocks, ephemeral=ephemeral, **kwargs)\n\n async def reply_scheduled(\n self,\n when: datetime,\n text: str,\n attachments: Sequence[Attachment] | Sequence[dict[str, Any]] | None = None,\n blocks: Sequence[Block] | Sequence[dict[str, Any]] | None = None,\n in_thread: bool = False,\n **kwargs: Any,\n ) -> AsyncSlackResponse:\n \"\"\"Schedule a reply and send it\n\n This is the scheduled version of [`reply()`][machine.plugins.message.Message.reply].\n It behaves the same, but will send the reply at the scheduled time.\n\n Args:\n when: when you want the message to be sent, as :py:class:`datetime.datetime` instance\n text: message text\n attachments: optional attachments (see [attachments](https://api.slack.com/docs/message-attachments))\n blocks: optional blocks (see [blocks](https://api.slack.com/reference/block-kit/blocks))\n in_thread: `True/False` wether to reply to the original message in-thread\n\n Returns:\n Dictionary deserialized from [chat.scheduleMessage](https://api.slack.com/methods/chat.scheduleMessage)\n response.\n \"\"\"\n if in_thread:\n return await self.say_scheduled(\n when, text, attachments=attachments, blocks=blocks, thread_ts=self.ts, **kwargs\n )\n else:\n text = cast(str, self._create_reply(text))\n return await self.say_scheduled(when, text, attachments=attachments, blocks=blocks, **kwargs)\n\n async def reply_dm(\n self,\n text: str | None = None,\n attachments: Sequence[Attachment] | Sequence[dict[str, Any]] | None = None,\n blocks: Sequence[Block] | Sequence[dict[str, Any]] | None = None,\n **kwargs: Any,\n ) -> AsyncSlackResponse:\n \"\"\"Reply to the sender of the original message with a DM\n\n Reply in a Direct Message to the sender of the original message by opening a DM channel and\n sending a message to it. Allows for rich formatting using [blocks] and/or [attachments].\n You can provide blocks and attachments as Python dicts or you can use the\n [convenience classes] that the underlying slack client provides.\n Any extra kwargs you provide, will be passed on directly to the [chat.postMessage] request.\n\n [attachments]: https://api.slack.com/docs/message-attachments\n [blocks]: https://api.slack.com/reference/block-kit/blocks\n [convenience classes]:\n https://github.com/slackapi/python-slackclient/tree/master/slack/web/classes\n [chat.postMessage]: https://api.slack.com/methods/chat.postMessage\n\n Args:\n text: message text\n attachments: optional attachments (see [attachments](https://api.slack.com/docs/message-attachments))\n blocks: optional blocks (see [blocks](https://api.slack.com/reference/block-kit/blocks))\n\n Returns:\n Dictionary deserialized from [chat.postMessage](https://api.slack.com/methods/chat.postMessage) response.\n \"\"\"\n return await self._client.send_dm(self.sender.id, text, attachments=attachments, blocks=blocks, **kwargs)\n\n async def reply_dm_scheduled(\n self,\n when: datetime,\n text: str,\n attachments: Sequence[Attachment] | Sequence[dict[str, Any]] | None = None,\n blocks: Sequence[Block] | Sequence[dict[str, Any]] | None = None,\n **kwargs: Any,\n ) -> AsyncSlackResponse:\n \"\"\"Schedule a DM reply and send it\n\n This is the scheduled version of [`reply_dm()`][machine.plugins.message.Message.reply_dm].\n It behaves the same, but will send the DM at the scheduled time.\n\n Args:\n when: when you want the message to be sent, as :py:class:`datetime.datetime` instance\n text: message text\n attachments: optional attachments (see [attachments](https://api.slack.com/docs/message-attachments))\n blocks: optional blocks (see [blocks](https://api.slack.com/reference/block-kit/blocks))\n\n Returns:\n Dictionary deserialized from [chat.scheduleMessage](https://api.slack.com/methods/chat.scheduleMessage)\n response.\n \"\"\"\n return await self._client.send_dm_scheduled(\n when, self.sender.id, text=text, attachments=attachments, blocks=blocks, **kwargs\n )\n\n async def react(self, emoji: str) -> AsyncSlackResponse:\n \"\"\"React to the original message\n\n Add a reaction to the original message\n\n Args:\n emoji: what emoji to react with (should be a string, like 'angel', 'thumbsup', etc.)\n\n Returns:\n Dictionary deserialized from [reactions.add](https://api.slack.com/methods/reactions.add) response.\n \"\"\"\n return await self._client.react(self.channel.id, self._msg_event[\"ts\"], emoji)\n\n def _create_reply(self, text: str | None) -> str | None:\n if not self.is_dm and text is not None:\n return f\"{self.at_sender}: {text}\"\n else:\n return text\n\n async def pin_message(self) -> AsyncSlackResponse:\n \"\"\"Pin message\n\n Pin the current message in the channel it was posted in\n\n Returns:\n Dictionary deserialized from [pins.add](https://api.slack.com/methods/pins.add) response.\n \"\"\"\n return await self._client.pin_message(self.channel, self.ts)\n\n def __str__(self) -> str:\n if self.channel.is_im:\n message = f\"Message '{self.text}', sent by user @{self.sender.profile.real_name} in DM\"\n else:\n message = (\n f\"Message '{self.text}', sent by user @{self.sender.profile.real_name} in channel #{self.channel.name}\"\n )\n return message\n\n def __repr__(self) -> str:\n return f\"Message(text={self.text!r}, sender={self.sender.profile.real_name!r}, channel={self.channel.name!r})\"", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 15115}, "tests/handlers/test_message_handler.py::62": {"resolved_imports": ["src/machine/handlers/message_handler.py", "src/machine/plugins/message.py"], "used_names": ["_check_bot_mention", "generate_message_matcher"], "enclosing_function": "test_check_bot_mention", "extracted_code": "# Source: src/machine/handlers/message_handler.py\ndef generate_message_matcher(settings: Mapping) -> re.Pattern[str]:\n alias_regex = \"\"\n if \"ALIASES\" in settings:\n logger.debug(\"Setting aliases to %s\", settings[\"ALIASES\"])\n alias_alternatives = \"|\".join([re.escape(alias) for alias in settings[\"ALIASES\"].split(\",\")])\n alias_regex = f\"|(?P<alias>{alias_alternatives})\"\n return re.compile(\n rf\"^(?:<@(?P<atuser>\\w+)>:?|(?P<username>\\w+):{alias_regex}) ?(?P<text>.*)$\",\n re.DOTALL,\n )\n\ndef _check_bot_mention(\n event: dict[str, Any], bot_name: str, bot_id: str, message_matcher: re.Pattern[str]\n) -> dict[str, Any] | None:\n full_text = event.get(\"text\", \"\")\n channel_type = event[\"channel_type\"]\n m = message_matcher.match(full_text)\n\n if channel_type == \"channel\" or channel_type == \"group\":\n if not m:\n return None\n\n matches = m.groupdict()\n\n atuser = matches.get(\"atuser\")\n username = matches.get(\"username\")\n text = matches.get(\"text\")\n alias = matches.get(\"alias\")\n\n if alias:\n atuser = bot_id\n\n if atuser != bot_id and username != bot_name:\n # a channel message at other user\n return None\n\n event[\"text\"] = text\n else:\n if m:\n event[\"text\"] = m.groupdict().get(\"text\", None)\n return event", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 1385}, "tests/handlers/test_message_handler.py::24": {"resolved_imports": ["src/machine/handlers/message_handler.py", "src/machine/plugins/message.py"], "used_names": ["generate_message_matcher", "re"], "enclosing_function": "test_generate_message_matcher", "extracted_code": "# Source: src/machine/handlers/message_handler.py\ndef generate_message_matcher(settings: Mapping) -> re.Pattern[str]:\n alias_regex = \"\"\n if \"ALIASES\" in settings:\n logger.debug(\"Setting aliases to %s\", settings[\"ALIASES\"])\n alias_alternatives = \"|\".join([re.escape(alias) for alias in settings[\"ALIASES\"].split(\",\")])\n alias_regex = f\"|(?P<alias>{alias_alternatives})\"\n return re.compile(\n rf\"^(?:<@(?P<atuser>\\w+)>:?|(?P<username>\\w+):{alias_regex}) ?(?P<text>.*)$\",\n re.DOTALL,\n )", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 529}, "tests/handlers/test_message_handler.py::27": {"resolved_imports": ["src/machine/handlers/message_handler.py", "src/machine/plugins/message.py"], "used_names": ["generate_message_matcher", "re"], "enclosing_function": "test_generate_message_matcher", "extracted_code": "# Source: src/machine/handlers/message_handler.py\ndef generate_message_matcher(settings: Mapping) -> re.Pattern[str]:\n alias_regex = \"\"\n if \"ALIASES\" in settings:\n logger.debug(\"Setting aliases to %s\", settings[\"ALIASES\"])\n alias_alternatives = \"|\".join([re.escape(alias) for alias in settings[\"ALIASES\"].split(\",\")])\n alias_regex = f\"|(?P<alias>{alias_alternatives})\"\n return re.compile(\n rf\"^(?:<@(?P<atuser>\\w+)>:?|(?P<username>\\w+):{alias_regex}) ?(?P<text>.*)$\",\n re.DOTALL,\n )", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 529}, "tests/handlers/test_message_handler.py::30": {"resolved_imports": ["src/machine/handlers/message_handler.py", "src/machine/plugins/message.py"], "used_names": ["generate_message_matcher", "re"], "enclosing_function": "test_generate_message_matcher", "extracted_code": "# Source: src/machine/handlers/message_handler.py\ndef generate_message_matcher(settings: Mapping) -> re.Pattern[str]:\n alias_regex = \"\"\n if \"ALIASES\" in settings:\n logger.debug(\"Setting aliases to %s\", settings[\"ALIASES\"])\n alias_alternatives = \"|\".join([re.escape(alias) for alias in settings[\"ALIASES\"].split(\",\")])\n alias_regex = f\"|(?P<alias>{alias_alternatives})\"\n return re.compile(\n rf\"^(?:<@(?P<atuser>\\w+)>:?|(?P<username>\\w+):{alias_regex}) ?(?P<text>.*)$\",\n re.DOTALL,\n )", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 529}, "tests/models/test_block_actions.py::23": {"resolved_imports": ["src/machine/models/interactive.py"], "used_names": ["BlockActionsPayload", "InteractivePayload"], "enclosing_function": "test_block_action_radio_button", "extracted_code": "# Source: src/machine/models/interactive.py\nclass BlockActionsPayload(TypedModel):\n type: Literal[\"block_actions\"]\n user: User\n api_app_id: str\n token: str\n container: Container\n trigger_id: str\n team: Team\n enterprise: Enterprise | None\n is_enterprise_install: bool\n channel: Channel | None = None\n message: Message | None = None\n view: View | None = None\n state: State | None = None\n response_url: str | None = None\n actions: list[Action]\n\n @model_validator(mode=\"after\")\n def validate_view_or_message(self) -> BlockActionsPayload:\n if self.view is None and self.message is None:\n raise ValueError(\"Either view or message must be present!\")\n if self.message is not None:\n if self.channel is None:\n raise ValueError(\"channel must be present when message is present!\")\n if self.state is None:\n raise ValueError(\"state must be present when message is present!\")\n if self.response_url is None:\n raise ValueError(\"response_url must be present when message is present!\")\n return self", "n_imports_parsed": 18, "n_files_resolved": 1, "n_chars_extracted": 1140}, "tests/models/test_channel.py::18": {"resolved_imports": ["src/machine/models/channel.py"], "used_names": ["Channel"], "enclosing_function": "test_identifier_without_name", "extracted_code": "# Source: src/machine/models/channel.py\nclass Channel(BaseModel):\n \"\"\"Channel model that represents a channel object from the Slack API\"\"\"\n\n model_config = ConfigDict(frozen=True)\n\n id: str\n name: Optional[str] = None\n created: int\n creator: Optional[str] = None\n is_archived: bool\n is_general: Optional[bool] = None\n name_normalized: Optional[str] = None\n is_shared: Optional[bool] = None\n is_org_shared: bool\n is_member: Optional[bool] = None\n is_private: Optional[bool] = None\n is_mpim: Optional[bool] = None\n is_channel: Optional[bool] = None\n is_group: Optional[bool] = None\n is_im: Optional[bool] = None\n user: Optional[str] = None\n topic: Optional[PurposeTopic] = None\n purpose: Optional[PurposeTopic] = None\n previous_names: Optional[list[str]] = None\n\n @property\n def identifier(self) -> str:\n \"\"\"Return the name of the channel if it exists, otherwise return the id\"\"\"\n if self.name:\n return self.name\n else:\n return self.id", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1045}, "tests/models/test_channel.py::24": {"resolved_imports": ["src/machine/models/channel.py"], "used_names": ["Channel"], "enclosing_function": "test_identifier_with_name", "extracted_code": "# Source: src/machine/models/channel.py\nclass Channel(BaseModel):\n \"\"\"Channel model that represents a channel object from the Slack API\"\"\"\n\n model_config = ConfigDict(frozen=True)\n\n id: str\n name: Optional[str] = None\n created: int\n creator: Optional[str] = None\n is_archived: bool\n is_general: Optional[bool] = None\n name_normalized: Optional[str] = None\n is_shared: Optional[bool] = None\n is_org_shared: bool\n is_member: Optional[bool] = None\n is_private: Optional[bool] = None\n is_mpim: Optional[bool] = None\n is_channel: Optional[bool] = None\n is_group: Optional[bool] = None\n is_im: Optional[bool] = None\n user: Optional[str] = None\n topic: Optional[PurposeTopic] = None\n purpose: Optional[PurposeTopic] = None\n previous_names: Optional[list[str]] = None\n\n @property\n def identifier(self) -> str:\n \"\"\"Return the name of the channel if it exists, otherwise return the id\"\"\"\n if self.name:\n return self.name\n else:\n return self.id", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1045}, "tests/models/test_user.py::25": {"resolved_imports": ["src/machine/models/user.py"], "used_names": [], "enclosing_function": "test_fmt_mention", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/models/test_views.py::8": {"resolved_imports": ["src/machine/models/interactive.py"], "used_names": ["InteractivePayload", "ViewSubmissionPayload"], "enclosing_function": "test_view_submission", "extracted_code": "# Source: src/machine/models/interactive.py\nclass ViewSubmissionPayload(TypedModel):\n type: Literal[\"view_submission\"]\n team: Team\n user: User\n view: View\n enterprise: Enterprise | None\n api_app_id: str\n token: str\n trigger_id: str\n response_urls: list[ResponseUrlForView]\n is_enterprise_install: bool", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 331}, "tests/plugins/test_decorators.py::288": {"resolved_imports": ["src/machine/plugins/__init__.py", "src/machine/plugins/decorators.py", "src/machine/plugins/metadata.py"], "used_names": ["ee"], "enclosing_function": "test_on", "extracted_code": "# Source: src/machine/plugins/__init__.py\nee = AsyncIOEventEmitter()", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 68}, "tests/plugins/test_decorators.py::267": {"resolved_imports": ["src/machine/plugins/__init__.py", "src/machine/plugins/decorators.py", "src/machine/plugins/metadata.py"], "used_names": ["schedule"], "enclosing_function": "test_schedule", "extracted_code": "# Source: src/machine/plugins/decorators.py\ndef schedule(\n year: int | str | None = None,\n month: int | str | None = None,\n day: int | str | None = None,\n week: int | str | None = None,\n day_of_week: int | str | None = None,\n hour: int | str | None = None,\n minute: int | str | None = None,\n second: int | str | None = None,\n start_date: datetime | str | None = None,\n end_date: datetime | str | None = None,\n timezone: tzinfo | str | None = None,\n) -> Callable[[Callable[P, R]], DecoratedPluginFunc[P, R]]:\n \"\"\"Schedule a function to be executed according to a crontab-like schedule\n\n The decorated function will be executed according to the schedule provided. Slack Machine uses\n APScheduler under the hood for scheduling. For more information on the interpretation of the\n provided parameters, see [`CronTrigger`][apscheduler.triggers.cron.CronTrigger]\n\n Args:\n year: 4-digit year\n month: month (1-12)\n day: day of the (1-31)\n week: ISO week (1-53)\n day_of_week: number or name of weekday (0-6 or mon,tue,wed,thu,fri,sat,sun)\n hour: hour (0-23)\n minute: minute (0-59)\n second: second (0-59)\n start_date: earliest possible date/time to trigger on (inclusive)\n end_date: latest possible date/time to trigger on (inclusive)\n timezone: time zone to use for the date/time calculations (defaults to scheduler timezone)\n\n Returns:\n wrapped method\n \"\"\"\n kwargs = locals()\n\n def schedule_decorator(f: Callable[P, R]) -> DecoratedPluginFunc[P, R]:\n fn = cast(DecoratedPluginFunc, f)\n fn.metadata = getattr(f, \"metadata\", Metadata())\n fn.metadata.plugin_actions.schedule = kwargs\n return fn\n\n return schedule_decorator", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 1785}, "tests/plugins/test_decorators.py::282": {"resolved_imports": ["src/machine/plugins/__init__.py", "src/machine/plugins/decorators.py", "src/machine/plugins/metadata.py"], "used_names": ["MatcherConfig", "listen_to", "process", "re", "respond_to"], "enclosing_function": "test_mulitple_decorators", "extracted_code": "# Source: src/machine/plugins/decorators.py\ndef process(slack_event_type: str) -> Callable[[Callable[P, R]], DecoratedPluginFunc[P, R]]:\n \"\"\"Process Slack events of a specific type\n\n This decorator will enable a Plugin method to process [Slack events] of a specific type. The\n Plugin method will be called for each event of the specified type that the bot receives.\n The received event will be passed to the method when called.\n\n [Slack events]: https://api.slack.com/events\n\n Args:\n slack_event_type: type of event the method needs to process. Can be any event supported\n by the [Events API](https://api.slack.com/events?filter=Events)\n\n Returns:\n wrapped method\n \"\"\"\n\n def process_decorator(f: Callable[P, R]) -> DecoratedPluginFunc[P, R]:\n fn = cast(DecoratedPluginFunc, f)\n fn.metadata = getattr(f, \"metadata\", Metadata())\n fn.metadata.plugin_actions.process.append(slack_event_type)\n return fn\n\n return process_decorator\n\ndef listen_to(\n regex: str, flags: re.RegexFlag | int = re.IGNORECASE, handle_message_changed: bool = False\n) -> Callable[[Callable[P, R]], DecoratedPluginFunc[P, R]]:\n \"\"\"Listen to messages matching a regex pattern\n\n This decorator will enable a Plugin method to listen to messages that match a regex pattern.\n The Plugin method will be called for each message that matches the specified regex pattern.\n The received [`Message`][machine.plugins.message.Message] will be passed to the method when called.\n Named groups can be used in the regex pattern, to catch specific parts of the message. These\n groups will be passed to the method as keyword arguments when called.\n\n Args:\n regex: regex pattern to listen for\n flags: regex flags to apply when matching\n handle_message_changed: if changed messages should trigger the decorated function\n\n Returns:\n wrapped method\n \"\"\"\n\n def listen_to_decorator(f: Callable[P, R]) -> DecoratedPluginFunc[P, R]:\n fn = cast(DecoratedPluginFunc, f)\n fn.metadata = getattr(f, \"metadata\", Metadata())\n fn.metadata.plugin_actions.listen_to.append(MatcherConfig(re.compile(regex, flags), handle_message_changed))\n return fn\n\n return listen_to_decorator\n\ndef respond_to(\n regex: str, flags: re.RegexFlag | int = re.IGNORECASE, handle_message_changed: bool = False\n) -> Callable[[Callable[P, R]], DecoratedPluginFunc[P, R]]:\n \"\"\"Listen to messages mentioning the bot and matching a regex pattern\n\n This decorator will enable a Plugin method to listen to messages that are directed to the bot\n (ie. message starts by mentioning the bot) and match a regex pattern.\n The Plugin method will be called for each message that mentions the bot and matches the\n specified regex pattern. The received [`Message`][machine.plugins.message.Message] will be passed\n to the method when called. Named groups can be used in the regex pattern, to catch specific\n parts of the message. These groups will be passed to the method as keyword arguments when\n called.\n\n Args:\n regex: regex pattern to listen for\n flags: regex flags to apply when matching\n handle_message_changed: if changed messages should trigger the decorated function\n\n Returns:\n wrapped method\n \"\"\"\n\n def respond_to_decorator(f: Callable[P, R]) -> DecoratedPluginFunc[P, R]:\n fn = cast(DecoratedPluginFunc, f)\n fn.metadata = getattr(f, \"metadata\", Metadata())\n fn.metadata.plugin_actions.respond_to.append(MatcherConfig(re.compile(regex, flags), handle_message_changed))\n return fn\n\n return respond_to_decorator\n\n\n# Source: src/machine/plugins/metadata.py\nclass MatcherConfig:\n regex: re.Pattern[str]\n handle_changed_message: bool = False", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 3818}, "tests/plugins/test_decorators.py::265": {"resolved_imports": ["src/machine/plugins/__init__.py", "src/machine/plugins/decorators.py", "src/machine/plugins/metadata.py"], "used_names": ["schedule"], "enclosing_function": "test_schedule", "extracted_code": "# Source: src/machine/plugins/decorators.py\ndef schedule(\n year: int | str | None = None,\n month: int | str | None = None,\n day: int | str | None = None,\n week: int | str | None = None,\n day_of_week: int | str | None = None,\n hour: int | str | None = None,\n minute: int | str | None = None,\n second: int | str | None = None,\n start_date: datetime | str | None = None,\n end_date: datetime | str | None = None,\n timezone: tzinfo | str | None = None,\n) -> Callable[[Callable[P, R]], DecoratedPluginFunc[P, R]]:\n \"\"\"Schedule a function to be executed according to a crontab-like schedule\n\n The decorated function will be executed according to the schedule provided. Slack Machine uses\n APScheduler under the hood for scheduling. For more information on the interpretation of the\n provided parameters, see [`CronTrigger`][apscheduler.triggers.cron.CronTrigger]\n\n Args:\n year: 4-digit year\n month: month (1-12)\n day: day of the (1-31)\n week: ISO week (1-53)\n day_of_week: number or name of weekday (0-6 or mon,tue,wed,thu,fri,sat,sun)\n hour: hour (0-23)\n minute: minute (0-59)\n second: second (0-59)\n start_date: earliest possible date/time to trigger on (inclusive)\n end_date: latest possible date/time to trigger on (inclusive)\n timezone: time zone to use for the date/time calculations (defaults to scheduler timezone)\n\n Returns:\n wrapped method\n \"\"\"\n kwargs = locals()\n\n def schedule_decorator(f: Callable[P, R]) -> DecoratedPluginFunc[P, R]:\n fn = cast(DecoratedPluginFunc, f)\n fn.metadata = getattr(f, \"metadata\", Metadata())\n fn.metadata.plugin_actions.schedule = kwargs\n return fn\n\n return schedule_decorator", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 1785}, "tests/plugins/test_decorators.py::289": {"resolved_imports": ["src/machine/plugins/__init__.py", "src/machine/plugins/decorators.py", "src/machine/plugins/metadata.py"], "used_names": ["ee"], "enclosing_function": "test_on", "extracted_code": "# Source: src/machine/plugins/__init__.py\nee = AsyncIOEventEmitter()", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 68}, "tests/plugins/test_decorators.py::266": {"resolved_imports": ["src/machine/plugins/__init__.py", "src/machine/plugins/decorators.py", "src/machine/plugins/metadata.py"], "used_names": ["schedule"], "enclosing_function": "test_schedule", "extracted_code": "# Source: src/machine/plugins/decorators.py\ndef schedule(\n year: int | str | None = None,\n month: int | str | None = None,\n day: int | str | None = None,\n week: int | str | None = None,\n day_of_week: int | str | None = None,\n hour: int | str | None = None,\n minute: int | str | None = None,\n second: int | str | None = None,\n start_date: datetime | str | None = None,\n end_date: datetime | str | None = None,\n timezone: tzinfo | str | None = None,\n) -> Callable[[Callable[P, R]], DecoratedPluginFunc[P, R]]:\n \"\"\"Schedule a function to be executed according to a crontab-like schedule\n\n The decorated function will be executed according to the schedule provided. Slack Machine uses\n APScheduler under the hood for scheduling. For more information on the interpretation of the\n provided parameters, see [`CronTrigger`][apscheduler.triggers.cron.CronTrigger]\n\n Args:\n year: 4-digit year\n month: month (1-12)\n day: day of the (1-31)\n week: ISO week (1-53)\n day_of_week: number or name of weekday (0-6 or mon,tue,wed,thu,fri,sat,sun)\n hour: hour (0-23)\n minute: minute (0-59)\n second: second (0-59)\n start_date: earliest possible date/time to trigger on (inclusive)\n end_date: latest possible date/time to trigger on (inclusive)\n timezone: time zone to use for the date/time calculations (defaults to scheduler timezone)\n\n Returns:\n wrapped method\n \"\"\"\n kwargs = locals()\n\n def schedule_decorator(f: Callable[P, R]) -> DecoratedPluginFunc[P, R]:\n fn = cast(DecoratedPluginFunc, f)\n fn.metadata = getattr(f, \"metadata\", Metadata())\n fn.metadata.plugin_actions.schedule = kwargs\n return fn\n\n return schedule_decorator", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 1785}, "tests/plugins/test_decorators.py::217": {"resolved_imports": ["src/machine/plugins/__init__.py", "src/machine/plugins/decorators.py", "src/machine/plugins/metadata.py"], "used_names": ["process"], "enclosing_function": "test_process", "extracted_code": "# Source: src/machine/plugins/decorators.py\ndef process(slack_event_type: str) -> Callable[[Callable[P, R]], DecoratedPluginFunc[P, R]]:\n \"\"\"Process Slack events of a specific type\n\n This decorator will enable a Plugin method to process [Slack events] of a specific type. The\n Plugin method will be called for each event of the specified type that the bot receives.\n The received event will be passed to the method when called.\n\n [Slack events]: https://api.slack.com/events\n\n Args:\n slack_event_type: type of event the method needs to process. Can be any event supported\n by the [Events API](https://api.slack.com/events?filter=Events)\n\n Returns:\n wrapped method\n \"\"\"\n\n def process_decorator(f: Callable[P, R]) -> DecoratedPluginFunc[P, R]:\n fn = cast(DecoratedPluginFunc, f)\n fn.metadata = getattr(f, \"metadata\", Metadata())\n fn.metadata.plugin_actions.process.append(slack_event_type)\n return fn\n\n return process_decorator", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 1008}, "tests/plugins/test_decorators.py::286": {"resolved_imports": ["src/machine/plugins/__init__.py", "src/machine/plugins/decorators.py", "src/machine/plugins/metadata.py"], "used_names": ["ee"], "enclosing_function": "test_on", "extracted_code": "# Source: src/machine/plugins/__init__.py\nee = AsyncIOEventEmitter()", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 68}, "tests/plugins/test_decorators.py::242": {"resolved_imports": ["src/machine/plugins/__init__.py", "src/machine/plugins/decorators.py", "src/machine/plugins/metadata.py"], "used_names": ["CommandConfig"], "enclosing_function": "test_command", "extracted_code": "# Source: src/machine/plugins/metadata.py\nclass CommandConfig:\n command: str\n is_generator: bool = False", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 110}, "tests/plugins/test_decorators.py::328": {"resolved_imports": ["src/machine/plugins/__init__.py", "src/machine/plugins/decorators.py", "src/machine/plugins/metadata.py"], "used_names": ["ModalConfig"], "enclosing_function": "test_modal", "extracted_code": "# Source: src/machine/plugins/metadata.py\nclass ModalConfig:\n callback_id: Union[re.Pattern[str], str]\n is_generator: bool = False", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 136}, "tests/plugins/test_decorators.py::249": {"resolved_imports": ["src/machine/plugins/__init__.py", "src/machine/plugins/decorators.py", "src/machine/plugins/metadata.py"], "used_names": ["CommandConfig"], "enclosing_function": "test_command_no_slash", "extracted_code": "# Source: src/machine/plugins/metadata.py\nclass CommandConfig:\n command: str\n is_generator: bool = False", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 110}, "tests/plugins/test_decorators.py::385": {"resolved_imports": ["src/machine/plugins/__init__.py", "src/machine/plugins/decorators.py", "src/machine/plugins/metadata.py"], "used_names": ["required_settings"], "enclosing_function": "test_required_settings_str", "extracted_code": "# Source: src/machine/plugins/decorators.py\ndef required_settings(settings: list[str] | str) -> Callable[[Callable[P, R]], DecoratedPluginFunc[P, R]]:\n \"\"\"Specify a required setting for a plugin or plugin method\n\n The settings specified with this decorator will be added to the required settings for the\n plugin. If one or more settings have not been defined by the user, the plugin will not be\n loaded and a warning will be written to the console upon startup.\n\n Args:\n settings: settings that are required (can be list of strings, or single string)\n\n Returns:\n wrapped method\n \"\"\"\n\n def required_settings_decorator(f_or_cls: Callable[P, R]) -> DecoratedPluginFunc[P, R]:\n casted_f_or_cls = cast(DecoratedPluginFunc, f_or_cls)\n casted_f_or_cls.metadata = getattr(f_or_cls, \"metadata\", Metadata())\n if isinstance(settings, list):\n casted_f_or_cls.metadata.required_settings.extend(settings)\n elif isinstance(settings, str):\n casted_f_or_cls.metadata.required_settings.append(settings)\n return casted_f_or_cls\n\n return required_settings_decorator", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 1143}, "tests/plugins/test_decorators.py::402": {"resolved_imports": ["src/machine/plugins/__init__.py", "src/machine/plugins/decorators.py", "src/machine/plugins/metadata.py"], "used_names": ["inspect", "required_settings"], "enclosing_function": "test_required_settings_for_class", "extracted_code": "# Source: src/machine/plugins/decorators.py\ndef required_settings(settings: list[str] | str) -> Callable[[Callable[P, R]], DecoratedPluginFunc[P, R]]:\n \"\"\"Specify a required setting for a plugin or plugin method\n\n The settings specified with this decorator will be added to the required settings for the\n plugin. If one or more settings have not been defined by the user, the plugin will not be\n loaded and a warning will be written to the console upon startup.\n\n Args:\n settings: settings that are required (can be list of strings, or single string)\n\n Returns:\n wrapped method\n \"\"\"\n\n def required_settings_decorator(f_or_cls: Callable[P, R]) -> DecoratedPluginFunc[P, R]:\n casted_f_or_cls = cast(DecoratedPluginFunc, f_or_cls)\n casted_f_or_cls.metadata = getattr(f_or_cls, \"metadata\", Metadata())\n if isinstance(settings, list):\n casted_f_or_cls.metadata.required_settings.extend(settings)\n elif isinstance(settings, str):\n casted_f_or_cls.metadata.required_settings.append(settings)\n return casted_f_or_cls\n\n return required_settings_decorator", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 1143}, "tests/plugins/test_decorators.py::377": {"resolved_imports": ["src/machine/plugins/__init__.py", "src/machine/plugins/decorators.py", "src/machine/plugins/metadata.py"], "used_names": ["required_settings"], "enclosing_function": "test_required_settings_list", "extracted_code": "# Source: src/machine/plugins/decorators.py\ndef required_settings(settings: list[str] | str) -> Callable[[Callable[P, R]], DecoratedPluginFunc[P, R]]:\n \"\"\"Specify a required setting for a plugin or plugin method\n\n The settings specified with this decorator will be added to the required settings for the\n plugin. If one or more settings have not been defined by the user, the plugin will not be\n loaded and a warning will be written to the console upon startup.\n\n Args:\n settings: settings that are required (can be list of strings, or single string)\n\n Returns:\n wrapped method\n \"\"\"\n\n def required_settings_decorator(f_or_cls: Callable[P, R]) -> DecoratedPluginFunc[P, R]:\n casted_f_or_cls = cast(DecoratedPluginFunc, f_or_cls)\n casted_f_or_cls.metadata = getattr(f_or_cls, \"metadata\", Metadata())\n if isinstance(settings, list):\n casted_f_or_cls.metadata.required_settings.extend(settings)\n elif isinstance(settings, str):\n casted_f_or_cls.metadata.required_settings.append(settings)\n return casted_f_or_cls\n\n return required_settings_decorator", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 1143}, "tests/plugins/test_decorators.py::392": {"resolved_imports": ["src/machine/plugins/__init__.py", "src/machine/plugins/decorators.py", "src/machine/plugins/metadata.py"], "used_names": ["required_settings"], "enclosing_function": "test_required_settings_multiple", "extracted_code": "# Source: src/machine/plugins/decorators.py\ndef required_settings(settings: list[str] | str) -> Callable[[Callable[P, R]], DecoratedPluginFunc[P, R]]:\n \"\"\"Specify a required setting for a plugin or plugin method\n\n The settings specified with this decorator will be added to the required settings for the\n plugin. If one or more settings have not been defined by the user, the plugin will not be\n loaded and a warning will be written to the console upon startup.\n\n Args:\n settings: settings that are required (can be list of strings, or single string)\n\n Returns:\n wrapped method\n \"\"\"\n\n def required_settings_decorator(f_or_cls: Callable[P, R]) -> DecoratedPluginFunc[P, R]:\n casted_f_or_cls = cast(DecoratedPluginFunc, f_or_cls)\n casted_f_or_cls.metadata = getattr(f_or_cls, \"metadata\", Metadata())\n if isinstance(settings, list):\n casted_f_or_cls.metadata.required_settings.extend(settings)\n elif isinstance(settings, str):\n casted_f_or_cls.metadata.required_settings.append(settings)\n return casted_f_or_cls\n\n return required_settings_decorator", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 1143}, "tests/storage/test_plugin_storage.py::29": {"resolved_imports": ["src/machine/storage/__init__.py", "src/machine/storage/backends/memory.py"], "used_names": ["pytest"], "enclosing_function": "test_inclusion", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/storage/test_plugin_storage.py::42": {"resolved_imports": ["src/machine/storage/__init__.py", "src/machine/storage/backends/memory.py"], "used_names": ["pytest"], "enclosing_function": "test_shared", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/storage/test_plugin_storage.py::36": {"resolved_imports": ["src/machine/storage/__init__.py", "src/machine/storage/backends/memory.py"], "used_names": ["pytest"], "enclosing_function": "test_retrieve", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/storage/test_plugin_storage.py::23": {"resolved_imports": ["src/machine/storage/__init__.py", "src/machine/storage/backends/memory.py"], "used_names": ["pytest"], "enclosing_function": "test_namespacing", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/storage/backends/test_memory_storage.py::15": {"resolved_imports": ["src/machine/storage/backends/memory.py"], "used_names": ["pytest"], "enclosing_function": "test_store_retrieve_values", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/storage/backends/test_memory_storage.py::40": {"resolved_imports": ["src/machine/storage/backends/memory.py"], "used_names": ["datetime", "pytest"], "enclosing_function": "test_expire_values", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/storage/backends/test_memory_storage.py::47": {"resolved_imports": ["src/machine/storage/backends/memory.py"], "used_names": ["pytest"], "enclosing_function": "test_inclusion", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/storage/backends/test_memory_storage.py::49": {"resolved_imports": ["src/machine/storage/backends/memory.py"], "used_names": ["pytest"], "enclosing_function": "test_inclusion", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/storage/backends/test_memory_storage.py::18": {"resolved_imports": ["src/machine/storage/backends/memory.py"], "used_names": ["pytest"], "enclosing_function": "test_store_retrieve_values", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/storage/backends/test_memory_storage.py::17": {"resolved_imports": ["src/machine/storage/backends/memory.py"], "used_names": ["pytest"], "enclosing_function": "test_store_retrieve_values", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/storage/backends/test_memory_storage.py::26": {"resolved_imports": ["src/machine/storage/backends/memory.py"], "used_names": ["pytest"], "enclosing_function": "test_delete_values", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/storage/backends/test_memory_storage.py::37": {"resolved_imports": ["src/machine/storage/backends/memory.py"], "used_names": ["datetime", "pytest"], "enclosing_function": "test_expire_values", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/storage/backends/test_redis_storage.py::32": {"resolved_imports": ["src/machine/storage/backends/redis.py"], "used_names": ["pytest"], "enclosing_function": "test_set", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/storage/backends/test_redis_storage.py::30": {"resolved_imports": ["src/machine/storage/backends/redis.py"], "used_names": ["pytest"], "enclosing_function": "test_set", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/storage/backends/test_redis_storage.py::56": {"resolved_imports": ["src/machine/storage/backends/redis.py"], "used_names": ["pytest"], "enclosing_function": "test_size", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/storage/backends/test_redis_storage.py::38": {"resolved_imports": ["src/machine/storage/backends/redis.py"], "used_names": ["pytest"], "enclosing_function": "test_get", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/storage/backends/test_sqlite_storage.py::68": {"resolved_imports": [], "used_names": ["SQLiteStorage", "pytest"], "enclosing_function": "test_size", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/storage/backends/test_sqlite_storage.py::71": {"resolved_imports": [], "used_names": ["SQLiteStorage", "pytest"], "enclosing_function": "test_size", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/storage/backends/test_sqlite_storage.py::56": {"resolved_imports": [], "used_names": ["SQLiteStorage", "pytest"], "enclosing_function": "test_expire_values", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/storage/backends/test_sqlite_storage.py::32": {"resolved_imports": [], "used_names": ["SQLiteStorage", "pytest"], "enclosing_function": "test_set_and_get", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/storage/backends/test_sqlite_storage.py::54": {"resolved_imports": [], "used_names": ["SQLiteStorage", "pytest"], "enclosing_function": "test_expire_values", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/storage/backends/test_sqlite_storage.py::53": {"resolved_imports": [], "used_names": ["SQLiteStorage", "pytest"], "enclosing_function": "test_expire_values", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/utils/test_datetime.py::14": {"resolved_imports": ["src/machine/utils/datetime.py"], "used_names": ["ZoneInfo", "calculate_epoch", "datetime"], "enclosing_function": "test_calculate_epoch", "extracted_code": "# Source: src/machine/utils/datetime.py\ndef calculate_epoch(dt: datetime, tz: tzinfo) -> int:\n if dt.tzinfo is None or dt.tzinfo.utcoffset(dt) is None:\n dt = dt.replace(tzinfo=tz)\n ts = round(dt.timestamp())\n return ts", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 234}, "tests/utils/test_datetime.py::19": {"resolved_imports": ["src/machine/utils/datetime.py"], "used_names": ["ZoneInfo", "calculate_epoch", "datetime"], "enclosing_function": "test_calculate_epoch", "extracted_code": "# Source: src/machine/utils/datetime.py\ndef calculate_epoch(dt: datetime, tz: tzinfo) -> int:\n if dt.tzinfo is None or dt.tzinfo.utcoffset(dt) is None:\n dt = dt.replace(tzinfo=tz)\n ts = round(dt.timestamp())\n return ts", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 234}, "tests/utils/test_import_string.py::10": {"resolved_imports": ["src/machine/utils/module_loading.py"], "used_names": ["import_string", "inspect"], "enclosing_function": "test_import_all_classes", "extracted_code": "# Source: src/machine/utils/module_loading.py\ndef import_string(dotted_path: str) -> list[tuple[str, type]]:\n \"\"\"\n Import all Classes from the module specified by\n the dotted_path. If dotted_path is not a module, try\n importing it as a member of a module instead\n\n returns: list of classes or list of single class\n \"\"\"\n\n try:\n module = import_module(dotted_path)\n return [(f\"{dotted_path}.{name}\", cls) for name, cls in inspect.getmembers(module, predicate=inspect.isclass)]\n except ImportError as exc:\n try:\n module_path, class_name = dotted_path.rsplit(\".\", 1)\n module = import_module(module_path)\n return [(f\"{module_path}.{class_name}\", getattr(module, class_name))]\n except (ImportError, AttributeError):\n msg = f\"{dotted_path} doesn't look like a module or class\"\n raise ImportError(msg) from exc", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 909}, "tests/utils/test_import_string.py::24": {"resolved_imports": ["src/machine/utils/module_loading.py"], "used_names": ["import_string"], "enclosing_function": "test_import_specific_class", "extracted_code": "# Source: src/machine/utils/module_loading.py\ndef import_string(dotted_path: str) -> list[tuple[str, type]]:\n \"\"\"\n Import all Classes from the module specified by\n the dotted_path. If dotted_path is not a module, try\n importing it as a member of a module instead\n\n returns: list of classes or list of single class\n \"\"\"\n\n try:\n module = import_module(dotted_path)\n return [(f\"{dotted_path}.{name}\", cls) for name, cls in inspect.getmembers(module, predicate=inspect.isclass)]\n except ImportError as exc:\n try:\n module_path, class_name = dotted_path.rsplit(\".\", 1)\n module = import_module(module_path)\n return [(f\"{module_path}.{class_name}\", getattr(module, class_name))]\n except (ImportError, AttributeError):\n msg = f\"{dotted_path} doesn't look like a module or class\"\n raise ImportError(msg) from exc", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 909}, "tests/utils/test_import_string.py::15": {"resolved_imports": ["src/machine/utils/module_loading.py"], "used_names": ["import_string", "inspect"], "enclosing_function": "test_import_all_classes", "extracted_code": "# Source: src/machine/utils/module_loading.py\ndef import_string(dotted_path: str) -> list[tuple[str, type]]:\n \"\"\"\n Import all Classes from the module specified by\n the dotted_path. If dotted_path is not a module, try\n importing it as a member of a module instead\n\n returns: list of classes or list of single class\n \"\"\"\n\n try:\n module = import_module(dotted_path)\n return [(f\"{dotted_path}.{name}\", cls) for name, cls in inspect.getmembers(module, predicate=inspect.isclass)]\n except ImportError as exc:\n try:\n module_path, class_name = dotted_path.rsplit(\".\", 1)\n module = import_module(module_path)\n return [(f\"{module_path}.{class_name}\", getattr(module, class_name))]\n except (ImportError, AttributeError):\n msg = f\"{dotted_path} doesn't look like a module or class\"\n raise ImportError(msg) from exc", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 909}, "tests/utils/test_import_string.py::18": {"resolved_imports": ["src/machine/utils/module_loading.py"], "used_names": ["import_string", "inspect"], "enclosing_function": "test_import_all_classes", "extracted_code": "# Source: src/machine/utils/module_loading.py\ndef import_string(dotted_path: str) -> list[tuple[str, type]]:\n \"\"\"\n Import all Classes from the module specified by\n the dotted_path. If dotted_path is not a module, try\n importing it as a member of a module instead\n\n returns: list of classes or list of single class\n \"\"\"\n\n try:\n module = import_module(dotted_path)\n return [(f\"{dotted_path}.{name}\", cls) for name, cls in inspect.getmembers(module, predicate=inspect.isclass)]\n except ImportError as exc:\n try:\n module_path, class_name = dotted_path.rsplit(\".\", 1)\n module = import_module(module_path)\n return [(f\"{module_path}.{class_name}\", getattr(module, class_name))]\n except (ImportError, AttributeError):\n msg = f\"{dotted_path} doesn't look like a module or class\"\n raise ImportError(msg) from exc", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 909}, "tests/utils/test_import_string.py::13": {"resolved_imports": ["src/machine/utils/module_loading.py"], "used_names": ["import_string", "inspect"], "enclosing_function": "test_import_all_classes", "extracted_code": "# Source: src/machine/utils/module_loading.py\ndef import_string(dotted_path: str) -> list[tuple[str, type]]:\n \"\"\"\n Import all Classes from the module specified by\n the dotted_path. If dotted_path is not a module, try\n importing it as a member of a module instead\n\n returns: list of classes or list of single class\n \"\"\"\n\n try:\n module = import_module(dotted_path)\n return [(f\"{dotted_path}.{name}\", cls) for name, cls in inspect.getmembers(module, predicate=inspect.isclass)]\n except ImportError as exc:\n try:\n module_path, class_name = dotted_path.rsplit(\".\", 1)\n module = import_module(module_path)\n return [(f\"{module_path}.{class_name}\", getattr(module, class_name))]\n except (ImportError, AttributeError):\n msg = f\"{dotted_path} doesn't look like a module or class\"\n raise ImportError(msg) from exc", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 909}, "tests/utils/test_import_string.py::30": {"resolved_imports": ["src/machine/utils/module_loading.py"], "used_names": ["import_string", "pytest"], "enclosing_function": "test_import_non_existing_module", "extracted_code": "# Source: src/machine/utils/module_loading.py\ndef import_string(dotted_path: str) -> list[tuple[str, type]]:\n \"\"\"\n Import all Classes from the module specified by\n the dotted_path. If dotted_path is not a module, try\n importing it as a member of a module instead\n\n returns: list of classes or list of single class\n \"\"\"\n\n try:\n module = import_module(dotted_path)\n return [(f\"{dotted_path}.{name}\", cls) for name, cls in inspect.getmembers(module, predicate=inspect.isclass)]\n except ImportError as exc:\n try:\n module_path, class_name = dotted_path.rsplit(\".\", 1)\n module = import_module(module_path)\n return [(f\"{module_path}.{class_name}\", getattr(module, class_name))]\n except (ImportError, AttributeError):\n msg = f\"{dotted_path} doesn't look like a module or class\"\n raise ImportError(msg) from exc", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 909}, "tests/utils/test_import_string.py::32": {"resolved_imports": ["src/machine/utils/module_loading.py"], "used_names": ["import_string", "pytest"], "enclosing_function": "test_import_non_existing_module", "extracted_code": "# Source: src/machine/utils/module_loading.py\ndef import_string(dotted_path: str) -> list[tuple[str, type]]:\n \"\"\"\n Import all Classes from the module specified by\n the dotted_path. If dotted_path is not a module, try\n importing it as a member of a module instead\n\n returns: list of classes or list of single class\n \"\"\"\n\n try:\n module = import_module(dotted_path)\n return [(f\"{dotted_path}.{name}\", cls) for name, cls in inspect.getmembers(module, predicate=inspect.isclass)]\n except ImportError as exc:\n try:\n module_path, class_name = dotted_path.rsplit(\".\", 1)\n module = import_module(module_path)\n return [(f\"{module_path}.{class_name}\", getattr(module, class_name))]\n except (ImportError, AttributeError):\n msg = f\"{dotted_path} doesn't look like a module or class\"\n raise ImportError(msg) from exc", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 909}, "tests/utils/test_import_string.py::25": {"resolved_imports": ["src/machine/utils/module_loading.py"], "used_names": ["import_string"], "enclosing_function": "test_import_specific_class", "extracted_code": "# Source: src/machine/utils/module_loading.py\ndef import_string(dotted_path: str) -> list[tuple[str, type]]:\n \"\"\"\n Import all Classes from the module specified by\n the dotted_path. If dotted_path is not a module, try\n importing it as a member of a module instead\n\n returns: list of classes or list of single class\n \"\"\"\n\n try:\n module = import_module(dotted_path)\n return [(f\"{dotted_path}.{name}\", cls) for name, cls in inspect.getmembers(module, predicate=inspect.isclass)]\n except ImportError as exc:\n try:\n module_path, class_name = dotted_path.rsplit(\".\", 1)\n module = import_module(module_path)\n return [(f\"{module_path}.{class_name}\", getattr(module, class_name))]\n except (ImportError, AttributeError):\n msg = f\"{dotted_path} doesn't look like a module or class\"\n raise ImportError(msg) from exc", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 909}, "tests/utils/test_utils.py::7": {"resolved_imports": ["src/machine/utils/__init__.py", "src/machine/utils/collections.py"], "used_names": ["CaseInsensitiveDict"], "enclosing_function": "test_CaseInsensitiveDict", "extracted_code": "# Source: src/machine/utils/collections.py\nclass CaseInsensitiveDict(MutableMapping[KT, VT]):\n \"\"\"\n A case-insensitive ``dict``-like object.\n Implements all methods and operations of\n ``collections.MutableMapping`` as well as dict's ``copy``. Also\n provides ``lower_items``.\n All keys are expected to be strings. The structure remembers the\n case of the last key to be set, and ``iter(instance)``,\n ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``\n will contain case-sensitive keys. However, querying and contains\n testing is case insensitive:\n cid = CaseInsensitiveDict()\n cid['Accept'] = 'application/json'\n cid['aCCEPT'] == 'application/json' # True\n list(cid) == ['Accept'] # True\n For example, ``headers['content-encoding']`` will return the\n value of a ``'Content-Encoding'`` response header, regardless\n of how the header name was originally stored.\n If the constructor, ``.update``, or equality comparison\n operations are given keys that have equal ``.lower()``s, the\n behavior is undefined.\n\n This class was copied from the ``requests`` package and made type-safe\n The original can be found at:\n https://github.com/requests/requests/blob/v1.2.3/requests/structures.py#L37\n \"\"\"\n\n def __init__(self, data: Mapping[KT, VT] | Iterable[tuple[KT, VT]] | None = None, **kwargs: VT):\n self._store: dict[KT, tuple[KT, VT]] = dict()\n if data is None:\n data = {}\n self.update(data, **kwargs)\n\n @staticmethod\n def _convert_key(key: KT) -> KT:\n lower_key = cast(KT, key.lower())\n return lower_key\n\n def __setitem__(self, key: KT, value: VT) -> None:\n # Use the lowercased key for lookups, but store the actual\n # key alongside the value.\n self._store[self._convert_key(key)] = (key, value)\n\n def __getitem__(self, key: KT) -> VT:\n return self._store[self._convert_key(key)][1]\n\n def __delitem__(self, key: KT) -> None:\n del self._store[self._convert_key(key)]\n\n def __iter__(self) -> Iterator[KT]:\n return (casedkey for casedkey, _ in self._store.values())\n\n def __len__(self) -> int:\n return len(self._store)\n\n def lower_items(self) -> Iterator[tuple[KT, VT]]:\n \"\"\"Like iteritems(), but with all lowercase keys.\"\"\"\n return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items())\n\n def __eq__(self, other: object) -> bool:\n if isinstance(other, Mapping):\n other = CaseInsensitiveDict(other)\n else:\n return NotImplemented\n # Compare insensitively\n return dict(self.lower_items()) == dict(other.lower_items())\n\n # Copy is required\n def copy(self) -> CaseInsensitiveDict[KT, VT]:\n return CaseInsensitiveDict(self._store.values())\n\n def __repr__(self) -> str:\n return f\"{self.__class__.__name__}({dict(self.items())!r})\"", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 2940}, "tests/utils/test_utils.py::15": {"resolved_imports": ["src/machine/utils/__init__.py", "src/machine/utils/collections.py"], "used_names": ["sizeof_fmt"], "enclosing_function": "test_size_fmt", "extracted_code": "# Source: src/machine/utils/__init__.py\ndef sizeof_fmt(num: float, suffix: str = \"B\") -> str:\n for unit in [\"\", \"K\", \"M\", \"G\", \"T\", \"P\", \"E\", \"Z\"]:\n if abs(num) < 1024.0:\n return f\"{num:3.1f}{unit}{suffix}\"\n num /= 1024.0\n return f\"{num:.1f}Yi{suffix}\"", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 283}, "tests/utils/test_utils.py::13": {"resolved_imports": ["src/machine/utils/__init__.py", "src/machine/utils/collections.py"], "used_names": ["sizeof_fmt"], "enclosing_function": "test_size_fmt", "extracted_code": "# Source: src/machine/utils/__init__.py\ndef sizeof_fmt(num: float, suffix: str = \"B\") -> str:\n for unit in [\"\", \"K\", \"M\", \"G\", \"T\", \"P\", \"E\", \"Z\"]:\n if abs(num) < 1024.0:\n return f\"{num:3.1f}{unit}{suffix}\"\n num /= 1024.0\n return f\"{num:.1f}Yi{suffix}\"", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 283}, "tests/utils/test_utils.py::17": {"resolved_imports": ["src/machine/utils/__init__.py", "src/machine/utils/collections.py"], "used_names": ["sizeof_fmt"], "enclosing_function": "test_size_fmt", "extracted_code": "# Source: src/machine/utils/__init__.py\ndef sizeof_fmt(num: float, suffix: str = \"B\") -> str:\n for unit in [\"\", \"K\", \"M\", \"G\", \"T\", \"P\", \"E\", \"Z\"]:\n if abs(num) < 1024.0:\n return f\"{num:3.1f}{unit}{suffix}\"\n num /= 1024.0\n return f\"{num:.1f}Yi{suffix}\"", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 283}}}