We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[FEATURE] Add args present argument to command filter 
### What kind of feature are you missing? Where do you notice a shortcoming of PTB?

There is currently no filter defined by us which simply checks if a command message has args, e.g. `start payload`

### Describe the solution you'd like

Add one argument to the command filter called `has_args` which checks if something comes after the command in the message.

### Describe alternatives you've considered

One can do this filter by themselves, but providing one would be nice

### Additional context

We could also start discussing if we want to provide some way to check the content of args, like a pattern match.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `telegram/ext/_commandhandler.py`
Content:
```
1 #!/usr/bin/env python
2 #
3 # A library that provides a Python interface to the Telegram Bot API
4 # Copyright (C) 2015-2023
5 # Leandro Toledo de Souza <devs@python-telegram-bot.org>
6 #
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Lesser Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU Lesser Public License for more details.
16 #
17 # You should have received a copy of the GNU Lesser Public License
18 # along with this program.  If not, see [http://www.gnu.org/licenses/].
19 """This module contains the CommandHandler class."""
20 import re
21 from typing import TYPE_CHECKING, Any, FrozenSet, List, Optional, Tuple, TypeVar, Union
22 
23 from telegram import MessageEntity, Update
24 from telegram._utils.defaultvalue import DEFAULT_TRUE
25 from telegram._utils.types import SCT, DVType
26 from telegram.ext import filters as filters_module
27 from telegram.ext._basehandler import BaseHandler
28 from telegram.ext._utils.types import CCT, FilterDataDict, HandlerCallback
29 
30 if TYPE_CHECKING:
31     from telegram.ext import Application
32 
33 RT = TypeVar("RT")
34 
35 
36 class CommandHandler(BaseHandler[Update, CCT]):
37     """BaseHandler class to handle Telegram commands.
38 
39     Commands are Telegram messages that start with ``/``, optionally followed by an ``@`` and the
40     bot's name and/or some additional text. The handler will add a :obj:`list` to the
41     :class:`CallbackContext` named :attr:`CallbackContext.args`. It will contain a list of strings,
42     which is the text following the command split on single or consecutive whitespace characters.
43 
44     By default, the handler listens to messages as well as edited messages. To change this behavior
45     use :attr:`~filters.UpdateType.EDITED_MESSAGE <telegram.ext.filters.UpdateType.EDITED_MESSAGE>`
46     in the filter argument.
47 
48     Note:
49         :class:`CommandHandler` does *not* handle (edited) channel posts and does *not* handle
50         commands that are part of a caption. Please use :class:`~telegram.ext.MessageHandler`
51         with a suitable combination of filters (e.g.
52         :attr:`telegram.ext.filters.UpdateType.CHANNEL_POSTS`,
53         :attr:`telegram.ext.filters.CAPTION` and :class:`telegram.ext.filters.Regex`) to handle
54         those messages.
55 
56     Warning:
57         When setting :paramref:`block` to :obj:`False`, you cannot rely on adding custom
58         attributes to :class:`telegram.ext.CallbackContext`. See its docs for more info.
59 
60     Examples:
61         * :any:`Timer Bot <examples.timerbot>`
62         * :any:`Error Handler Bot <examples.errorhandlerbot>`
63 
64     .. versionchanged:: 20.0
65 
66         * Renamed the attribute ``command`` to :attr:`commands`, which now is always a
67           :class:`frozenset`
68         * Updating the commands this handler listens to is no longer possible.
69 
70     Args:
71         command (:obj:`str` | Collection[:obj:`str`]):
72             The command or list of commands this handler should listen for. Case-insensitive.
73             Limitations are the same as for :attr:`telegram.BotCommand.command`.
74         callback (:term:`coroutine function`): The callback function for this handler. Will be
75             called when :meth:`check_update` has determined that an update should be processed by
76             this handler. Callback signature::
77 
78                 async def callback(update: Update, context: CallbackContext)
79 
80             The return value of the callback is usually ignored except for the special case of
81             :class:`telegram.ext.ConversationHandler`.
82         filters (:class:`telegram.ext.filters.BaseFilter`, optional): A filter inheriting from
83             :class:`telegram.ext.filters.BaseFilter`. Standard filters can be found in
84             :mod:`telegram.ext.filters`. Filters can be combined using bitwise
85             operators (``&`` for :keyword:`and`, ``|`` for :keyword:`or`, ``~`` for :keyword:`not`)
86         block (:obj:`bool`, optional): Determines whether the return value of the callback should
87             be awaited before processing the next handler in
88             :meth:`telegram.ext.Application.process_update`. Defaults to :obj:`True`.
89 
90             .. seealso:: :wiki:`Concurrency`
91 
92     Raises:
93         :exc:`ValueError`: When the command is too long or has illegal chars.
94 
95     Attributes:
96         commands (FrozenSet[:obj:`str`]): The set of commands this handler should listen for.
97         callback (:term:`coroutine function`): The callback function for this handler.
98         filters (:class:`telegram.ext.filters.BaseFilter`): Optional. Only allow updates with these
99             Filters.
100         block (:obj:`bool`): Determines whether the return value of the callback should be
101             awaited before processing the next handler in
102             :meth:`telegram.ext.Application.process_update`.
103     """
104 
105     __slots__ = ("commands", "filters")
106 
107     def __init__(
108         self,
109         command: SCT[str],
110         callback: HandlerCallback[Update, CCT, RT],
111         filters: Optional[filters_module.BaseFilter] = None,
112         block: DVType[bool] = DEFAULT_TRUE,
113     ):
114         super().__init__(callback, block=block)
115 
116         if isinstance(command, str):
117             commands = frozenset({command.lower()})
118         else:
119             commands = frozenset(x.lower() for x in command)
120         for comm in commands:
121             if not re.match(r"^[\da-z_]{1,32}$", comm):
122                 raise ValueError(f"Command `{comm}` is not a valid bot command")
123         self.commands: FrozenSet[str] = commands
124 
125         self.filters: filters_module.BaseFilter = (
126             filters if filters is not None else filters_module.UpdateType.MESSAGES
127         )
128 
129     def check_update(
130         self, update: object
131     ) -> Optional[Union[bool, Tuple[List[str], Optional[Union[bool, FilterDataDict]]]]]:
132         """Determines whether an update should be passed to this handler's :attr:`callback`.
133 
134         Args:
135             update (:class:`telegram.Update` | :obj:`object`): Incoming update.
136 
137         Returns:
138             :obj:`list`: The list of args for the handler.
139 
140         """
141         if isinstance(update, Update) and update.effective_message:
142             message = update.effective_message
143 
144             if (
145                 message.entities
146                 and message.entities[0].type == MessageEntity.BOT_COMMAND
147                 and message.entities[0].offset == 0
148                 and message.text
149                 and message.get_bot()
150             ):
151                 command = message.text[1 : message.entities[0].length]
152                 args = message.text.split()[1:]
153                 command_parts = command.split("@")
154                 command_parts.append(message.get_bot().username)
155 
156                 if not (
157                     command_parts[0].lower() in self.commands
158                     and command_parts[1].lower() == message.get_bot().username.lower()
159                 ):
160                     return None
161 
162                 filter_result = self.filters.check_update(update)
163                 if filter_result:
164                     return args, filter_result
165                 return False
166         return None
167 
168     def collect_additional_context(
169         self,
170         context: CCT,
171         update: Update,  # skipcq: BAN-B301
172         application: "Application[Any, CCT, Any, Any, Any, Any]",  # skipcq: BAN-B301
173         check_result: Optional[Union[bool, Tuple[List[str], Optional[bool]]]],
174     ) -> None:
175         """Add text after the command to :attr:`CallbackContext.args` as list, split on single
176         whitespaces and add output of data filters to :attr:`CallbackContext` as well.
177         """
178         if isinstance(check_result, tuple):
179             context.args = check_result[0]
180             if isinstance(check_result[1], dict):
181                 context.update(check_result[1])
182
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/telegram/ext/_commandhandler.py b/telegram/ext/_commandhandler.py
--- a/telegram/ext/_commandhandler.py
+++ b/telegram/ext/_commandhandler.py
@@ -88,6 +88,14 @@
             :meth:`telegram.ext.Application.process_update`. Defaults to :obj:`True`.
 
             .. seealso:: :wiki:`Concurrency`
+        has_args (:obj:`bool` | :obj:`int`, optional):
+            Determines whether the command handler should process the update or not.
+            If :obj:`True`, the handler will process any non-zero number of args.
+            If :obj:`False`, the handler will only process if there are no args.
+            if :obj:`int`, the handler will only process if there are exactly that many args.
+            Defaults to :obj:`None`, which means the handler will process any or no args.
+
+            .. versionadded:: NEXT.VERSION
 
     Raises:
         :exc:`ValueError`: When the command is too long or has illegal chars.
@@ -100,9 +108,14 @@
         block (:obj:`bool`): Determines whether the return value of the callback should be
             awaited before processing the next handler in
             :meth:`telegram.ext.Application.process_update`.
+        has_args (:obj:`bool` | :obj:`int` | None):
+            Optional argument, otherwise all implementations of :class:`CommandHandler` will break.
+            Defaults to :obj:`None`, which means the handler will process any args or no args.
+
+            .. versionadded:: NEXT.VERSION
     """
 
-    __slots__ = ("commands", "filters")
+    __slots__ = ("commands", "filters", "has_args")
 
     def __init__(
         self,
@@ -110,6 +123,7 @@
         callback: HandlerCallback[Update, CCT, RT],
         filters: Optional[filters_module.BaseFilter] = None,
         block: DVType[bool] = DEFAULT_TRUE,
+        has_args: Optional[Union[bool, int]] = None,
     ):
         super().__init__(callback, block=block)
 
@@ -126,6 +140,28 @@
             filters if filters is not None else filters_module.UpdateType.MESSAGES
         )
 
+        self.has_args: Optional[Union[bool, int]] = has_args
+
+        if (isinstance(self.has_args, int)) and (self.has_args < 0):
+            raise ValueError("CommandHandler argument has_args cannot be a negative integer")
+
+    def _check_correct_args(self, args: List[str]) -> Optional[bool]:
+        """Determines whether the args are correct for this handler. Implemented in check_update().
+        Args:
+            args (:obj:`list`): The args for the handler.
+        Returns:
+            :obj:`bool`: Whether the args are valid for this handler.
+        """
+        # pylint: disable=too-many-boolean-expressions
+        if (
+            (self.has_args is None)
+            or (self.has_args is True and args)
+            or (self.has_args is False and not args)
+            or (isinstance(self.has_args, int) and len(args) == self.has_args)
+        ):
+            return True
+        return False
+
     def check_update(
         self, update: object
     ) -> Optional[Union[bool, Tuple[List[str], Optional[Union[bool, FilterDataDict]]]]]:
@@ -159,6 +195,9 @@
                 ):
                     return None
 
+                if not self._check_correct_args(args):
+                    return None
+
                 filter_result = self.filters.check_update(update)
                 if filter_result:
                     return args, filter_result

{"golden_diff": "diff --git a/telegram/ext/_commandhandler.py b/telegram/ext/_commandhandler.py\n--- a/telegram/ext/_commandhandler.py\n+++ b/telegram/ext/_commandhandler.py\n@@ -88,6 +88,14 @@\n             :meth:`telegram.ext.Application.process_update`. Defaults to :obj:`True`.\n \n             .. seealso:: :wiki:`Concurrency`\n+        has_args (:obj:`bool` | :obj:`int`, optional):\n+            Determines whether the command handler should process the update or not.\n+            If :obj:`True`, the handler will process any non-zero number of args.\n+            If :obj:`False`, the handler will only process if there are no args.\n+            if :obj:`int`, the handler will only process if there are exactly that many args.\n+            Defaults to :obj:`None`, which means the handler will process any or no args.\n+\n+            .. versionadded:: NEXT.VERSION\n \n     Raises:\n         :exc:`ValueError`: When the command is too long or has illegal chars.\n@@ -100,9 +108,14 @@\n         block (:obj:`bool`): Determines whether the return value of the callback should be\n             awaited before processing the next handler in\n             :meth:`telegram.ext.Application.process_update`.\n+        has_args (:obj:`bool` | :obj:`int` | None):\n+            Optional argument, otherwise all implementations of :class:`CommandHandler` will break.\n+            Defaults to :obj:`None`, which means the handler will process any args or no args.\n+\n+            .. versionadded:: NEXT.VERSION\n     \"\"\"\n \n-    __slots__ = (\"commands\", \"filters\")\n+    __slots__ = (\"commands\", \"filters\", \"has_args\")\n \n     def __init__(\n         self,\n@@ -110,6 +123,7 @@\n         callback: HandlerCallback[Update, CCT, RT],\n         filters: Optional[filters_module.BaseFilter] = None,\n         block: DVType[bool] = DEFAULT_TRUE,\n+        has_args: Optional[Union[bool, int]] = None,\n     ):\n         super().__init__(callback, block=block)\n \n@@ -126,6 +140,28 @@\n             filters if filters is not None else filters_module.UpdateType.MESSAGES\n         )\n \n+        self.has_args: Optional[Union[bool, int]] = has_args\n+\n+        if (isinstance(self.has_args, int)) and (self.has_args < 0):\n+            raise ValueError(\"CommandHandler argument has_args cannot be a negative integer\")\n+\n+    def _check_correct_args(self, args: List[str]) -> Optional[bool]:\n+        \"\"\"Determines whether the args are correct for this handler. Implemented in check_update().\n+        Args:\n+            args (:obj:`list`): The args for the handler.\n+        Returns:\n+            :obj:`bool`: Whether the args are valid for this handler.\n+        \"\"\"\n+        # pylint: disable=too-many-boolean-expressions\n+        if (\n+            (self.has_args is None)\n+            or (self.has_args is True and args)\n+            or (self.has_args is False and not args)\n+            or (isinstance(self.has_args, int) and len(args) == self.has_args)\n+        ):\n+            return True\n+        return False\n+\n     def check_update(\n         self, update: object\n     ) -> Optional[Union[bool, Tuple[List[str], Optional[Union[bool, FilterDataDict]]]]]:\n@@ -159,6 +195,9 @@\n                 ):\n                     return None\n \n+                if not self._check_correct_args(args):\n+                    return None\n+\n                 filter_result = self.filters.check_update(update)\n                 if filter_result:\n                     return args, filter_result\n", "issue": "[FEATURE] Add args present argument to command filter \n### What kind of feature are you missing? Where do you notice a shortcoming of PTB?\n\nThere is currently no filter defined by us which simply checks if a command message has args, e.g. `start payload`\n\n### Describe the solution you'd like\n\nAdd one argument to the command filter called `has_args` which checks if something comes after the command in the message.\n\n### Describe alternatives you've considered\n\nOne can do this filter by themselves, but providing one would be nice\n\n### Additional context\n\nWe could also start discussing if we want to provide some way to check the content of args, like a pattern match.\n", "before_files": [{"content": "#!/usr/bin/env python\n#\n# A library that provides a Python interface to the Telegram Bot API\n# Copyright (C) 2015-2023\n# Leandro Toledo de Souza <devs@python-telegram-bot.org>\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU Lesser Public License for more details.\n#\n# You should have received a copy of the GNU Lesser Public License\n# along with this program.  If not, see [http://www.gnu.org/licenses/].\n\"\"\"This module contains the CommandHandler class.\"\"\"\nimport re\nfrom typing import TYPE_CHECKING, Any, FrozenSet, List, Optional, Tuple, TypeVar, Union\n\nfrom telegram import MessageEntity, Update\nfrom telegram._utils.defaultvalue import DEFAULT_TRUE\nfrom telegram._utils.types import SCT, DVType\nfrom telegram.ext import filters as filters_module\nfrom telegram.ext._basehandler import BaseHandler\nfrom telegram.ext._utils.types import CCT, FilterDataDict, HandlerCallback\n\nif TYPE_CHECKING:\n    from telegram.ext import Application\n\nRT = TypeVar(\"RT\")\n\n\nclass CommandHandler(BaseHandler[Update, CCT]):\n    \"\"\"BaseHandler class to handle Telegram commands.\n\n    Commands are Telegram messages that start with ``/``, optionally followed by an ``@`` and the\n    bot's name and/or some additional text. The handler will add a :obj:`list` to the\n    :class:`CallbackContext` named :attr:`CallbackContext.args`. It will contain a list of strings,\n    which is the text following the command split on single or consecutive whitespace characters.\n\n    By default, the handler listens to messages as well as edited messages. To change this behavior\n    use :attr:`~filters.UpdateType.EDITED_MESSAGE <telegram.ext.filters.UpdateType.EDITED_MESSAGE>`\n    in the filter argument.\n\n    Note:\n        :class:`CommandHandler` does *not* handle (edited) channel posts and does *not* handle\n        commands that are part of a caption. Please use :class:`~telegram.ext.MessageHandler`\n        with a suitable combination of filters (e.g.\n        :attr:`telegram.ext.filters.UpdateType.CHANNEL_POSTS`,\n        :attr:`telegram.ext.filters.CAPTION` and :class:`telegram.ext.filters.Regex`) to handle\n        those messages.\n\n    Warning:\n        When setting :paramref:`block` to :obj:`False`, you cannot rely on adding custom\n        attributes to :class:`telegram.ext.CallbackContext`. See its docs for more info.\n\n    Examples:\n        * :any:`Timer Bot <examples.timerbot>`\n        * :any:`Error Handler Bot <examples.errorhandlerbot>`\n\n    .. versionchanged:: 20.0\n\n        * Renamed the attribute ``command`` to :attr:`commands`, which now is always a\n          :class:`frozenset`\n        * Updating the commands this handler listens to is no longer possible.\n\n    Args:\n        command (:obj:`str` | Collection[:obj:`str`]):\n            The command or list of commands this handler should listen for. Case-insensitive.\n            Limitations are the same as for :attr:`telegram.BotCommand.command`.\n        callback (:term:`coroutine function`): The callback function for this handler. Will be\n            called when :meth:`check_update` has determined that an update should be processed by\n            this handler. Callback signature::\n\n                async def callback(update: Update, context: CallbackContext)\n\n            The return value of the callback is usually ignored except for the special case of\n            :class:`telegram.ext.ConversationHandler`.\n        filters (:class:`telegram.ext.filters.BaseFilter`, optional): A filter inheriting from\n            :class:`telegram.ext.filters.BaseFilter`. Standard filters can be found in\n            :mod:`telegram.ext.filters`. Filters can be combined using bitwise\n            operators (``&`` for :keyword:`and`, ``|`` for :keyword:`or`, ``~`` for :keyword:`not`)\n        block (:obj:`bool`, optional): Determines whether the return value of the callback should\n            be awaited before processing the next handler in\n            :meth:`telegram.ext.Application.process_update`. Defaults to :obj:`True`.\n\n            .. seealso:: :wiki:`Concurrency`\n\n    Raises:\n        :exc:`ValueError`: When the command is too long or has illegal chars.\n\n    Attributes:\n        commands (FrozenSet[:obj:`str`]): The set of commands this handler should listen for.\n        callback (:term:`coroutine function`): The callback function for this handler.\n        filters (:class:`telegram.ext.filters.BaseFilter`): Optional. Only allow updates with these\n            Filters.\n        block (:obj:`bool`): Determines whether the return value of the callback should be\n            awaited before processing the next handler in\n            :meth:`telegram.ext.Application.process_update`.\n    \"\"\"\n\n    __slots__ = (\"commands\", \"filters\")\n\n    def __init__(\n        self,\n        command: SCT[str],\n        callback: HandlerCallback[Update, CCT, RT],\n        filters: Optional[filters_module.BaseFilter] = None,\n        block: DVType[bool] = DEFAULT_TRUE,\n    ):\n        super().__init__(callback, block=block)\n\n        if isinstance(command, str):\n            commands = frozenset({command.lower()})\n        else:\n            commands = frozenset(x.lower() for x in command)\n        for comm in commands:\n            if not re.match(r\"^[\\da-z_]{1,32}$\", comm):\n                raise ValueError(f\"Command `{comm}` is not a valid bot command\")\n        self.commands: FrozenSet[str] = commands\n\n        self.filters: filters_module.BaseFilter = (\n            filters if filters is not None else filters_module.UpdateType.MESSAGES\n        )\n\n    def check_update(\n        self, update: object\n    ) -> Optional[Union[bool, Tuple[List[str], Optional[Union[bool, FilterDataDict]]]]]:\n        \"\"\"Determines whether an update should be passed to this handler's :attr:`callback`.\n\n        Args:\n            update (:class:`telegram.Update` | :obj:`object`): Incoming update.\n\n        Returns:\n            :obj:`list`: The list of args for the handler.\n\n        \"\"\"\n        if isinstance(update, Update) and update.effective_message:\n            message = update.effective_message\n\n            if (\n                message.entities\n                and message.entities[0].type == MessageEntity.BOT_COMMAND\n                and message.entities[0].offset == 0\n                and message.text\n                and message.get_bot()\n            ):\n                command = message.text[1 : message.entities[0].length]\n                args = message.text.split()[1:]\n                command_parts = command.split(\"@\")\n                command_parts.append(message.get_bot().username)\n\n                if not (\n                    command_parts[0].lower() in self.commands\n                    and command_parts[1].lower() == message.get_bot().username.lower()\n                ):\n                    return None\n\n                filter_result = self.filters.check_update(update)\n                if filter_result:\n                    return args, filter_result\n                return False\n        return None\n\n    def collect_additional_context(\n        self,\n        context: CCT,\n        update: Update,  # skipcq: BAN-B301\n        application: \"Application[Any, CCT, Any, Any, Any, Any]\",  # skipcq: BAN-B301\n        check_result: Optional[Union[bool, Tuple[List[str], Optional[bool]]]],\n    ) -> None:\n        \"\"\"Add text after the command to :attr:`CallbackContext.args` as list, split on single\n        whitespaces and add output of data filters to :attr:`CallbackContext` as well.\n        \"\"\"\n        if isinstance(check_result, tuple):\n            context.args = check_result[0]\n            if isinstance(check_result[1], dict):\n                context.update(check_result[1])\n", "path": "telegram/ext/_commandhandler.py"}], "after_files": [{"content": "#!/usr/bin/env python\n#\n# A library that provides a Python interface to the Telegram Bot API\n# Copyright (C) 2015-2023\n# Leandro Toledo de Souza <devs@python-telegram-bot.org>\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU Lesser Public License for more details.\n#\n# You should have received a copy of the GNU Lesser Public License\n# along with this program.  If not, see [http://www.gnu.org/licenses/].\n\"\"\"This module contains the CommandHandler class.\"\"\"\nimport re\nfrom typing import TYPE_CHECKING, Any, FrozenSet, List, Optional, Tuple, TypeVar, Union\n\nfrom telegram import MessageEntity, Update\nfrom telegram._utils.defaultvalue import DEFAULT_TRUE\nfrom telegram._utils.types import SCT, DVType\nfrom telegram.ext import filters as filters_module\nfrom telegram.ext._basehandler import BaseHandler\nfrom telegram.ext._utils.types import CCT, FilterDataDict, HandlerCallback\n\nif TYPE_CHECKING:\n    from telegram.ext import Application\n\nRT = TypeVar(\"RT\")\n\n\nclass CommandHandler(BaseHandler[Update, CCT]):\n    \"\"\"BaseHandler class to handle Telegram commands.\n\n    Commands are Telegram messages that start with ``/``, optionally followed by an ``@`` and the\n    bot's name and/or some additional text. The handler will add a :obj:`list` to the\n    :class:`CallbackContext` named :attr:`CallbackContext.args`. It will contain a list of strings,\n    which is the text following the command split on single or consecutive whitespace characters.\n\n    By default, the handler listens to messages as well as edited messages. To change this behavior\n    use :attr:`~filters.UpdateType.EDITED_MESSAGE <telegram.ext.filters.UpdateType.EDITED_MESSAGE>`\n    in the filter argument.\n\n    Note:\n        :class:`CommandHandler` does *not* handle (edited) channel posts and does *not* handle\n        commands that are part of a caption. Please use :class:`~telegram.ext.MessageHandler`\n        with a suitable combination of filters (e.g.\n        :attr:`telegram.ext.filters.UpdateType.CHANNEL_POSTS`,\n        :attr:`telegram.ext.filters.CAPTION` and :class:`telegram.ext.filters.Regex`) to handle\n        those messages.\n\n    Warning:\n        When setting :paramref:`block` to :obj:`False`, you cannot rely on adding custom\n        attributes to :class:`telegram.ext.CallbackContext`. See its docs for more info.\n\n    Examples:\n        * :any:`Timer Bot <examples.timerbot>`\n        * :any:`Error Handler Bot <examples.errorhandlerbot>`\n\n    .. versionchanged:: 20.0\n\n        * Renamed the attribute ``command`` to :attr:`commands`, which now is always a\n          :class:`frozenset`\n        * Updating the commands this handler listens to is no longer possible.\n\n    Args:\n        command (:obj:`str` | Collection[:obj:`str`]):\n            The command or list of commands this handler should listen for. Case-insensitive.\n            Limitations are the same as for :attr:`telegram.BotCommand.command`.\n        callback (:term:`coroutine function`): The callback function for this handler. Will be\n            called when :meth:`check_update` has determined that an update should be processed by\n            this handler. Callback signature::\n\n                async def callback(update: Update, context: CallbackContext)\n\n            The return value of the callback is usually ignored except for the special case of\n            :class:`telegram.ext.ConversationHandler`.\n        filters (:class:`telegram.ext.filters.BaseFilter`, optional): A filter inheriting from\n            :class:`telegram.ext.filters.BaseFilter`. Standard filters can be found in\n            :mod:`telegram.ext.filters`. Filters can be combined using bitwise\n            operators (``&`` for :keyword:`and`, ``|`` for :keyword:`or`, ``~`` for :keyword:`not`)\n        block (:obj:`bool`, optional): Determines whether the return value of the callback should\n            be awaited before processing the next handler in\n            :meth:`telegram.ext.Application.process_update`. Defaults to :obj:`True`.\n\n            .. seealso:: :wiki:`Concurrency`\n        has_args (:obj:`bool` | :obj:`int`, optional):\n            Determines whether the command handler should process the update or not.\n            If :obj:`True`, the handler will process any non-zero number of args.\n            If :obj:`False`, the handler will only process if there are no args.\n            if :obj:`int`, the handler will only process if there are exactly that many args.\n            Defaults to :obj:`None`, which means the handler will process any or no args.\n\n            .. versionadded:: NEXT.VERSION\n\n    Raises:\n        :exc:`ValueError`: When the command is too long or has illegal chars.\n\n    Attributes:\n        commands (FrozenSet[:obj:`str`]): The set of commands this handler should listen for.\n        callback (:term:`coroutine function`): The callback function for this handler.\n        filters (:class:`telegram.ext.filters.BaseFilter`): Optional. Only allow updates with these\n            Filters.\n        block (:obj:`bool`): Determines whether the return value of the callback should be\n            awaited before processing the next handler in\n            :meth:`telegram.ext.Application.process_update`.\n        has_args (:obj:`bool` | :obj:`int` | None):\n            Optional argument, otherwise all implementations of :class:`CommandHandler` will break.\n            Defaults to :obj:`None`, which means the handler will process any args or no args.\n\n            .. versionadded:: NEXT.VERSION\n    \"\"\"\n\n    __slots__ = (\"commands\", \"filters\", \"has_args\")\n\n    def __init__(\n        self,\n        command: SCT[str],\n        callback: HandlerCallback[Update, CCT, RT],\n        filters: Optional[filters_module.BaseFilter] = None,\n        block: DVType[bool] = DEFAULT_TRUE,\n        has_args: Optional[Union[bool, int]] = None,\n    ):\n        super().__init__(callback, block=block)\n\n        if isinstance(command, str):\n            commands = frozenset({command.lower()})\n        else:\n            commands = frozenset(x.lower() for x in command)\n        for comm in commands:\n            if not re.match(r\"^[\\da-z_]{1,32}$\", comm):\n                raise ValueError(f\"Command `{comm}` is not a valid bot command\")\n        self.commands: FrozenSet[str] = commands\n\n        self.filters: filters_module.BaseFilter = (\n            filters if filters is not None else filters_module.UpdateType.MESSAGES\n        )\n\n        self.has_args: Optional[Union[bool, int]] = has_args\n\n        if (isinstance(self.has_args, int)) and (self.has_args < 0):\n            raise ValueError(\"CommandHandler argument has_args cannot be a negative integer\")\n\n    def _check_correct_args(self, args: List[str]) -> Optional[bool]:\n        \"\"\"Determines whether the args are correct for this handler. Implemented in check_update().\n        Args:\n            args (:obj:`list`): The args for the handler.\n        Returns:\n            :obj:`bool`: Whether the args are valid for this handler.\n        \"\"\"\n        # pylint: disable=too-many-boolean-expressions\n        if (\n            (self.has_args is None)\n            or (self.has_args is True and args)\n            or (self.has_args is False and not args)\n            or (isinstance(self.has_args, int) and len(args) == self.has_args)\n        ):\n            return True\n        return False\n\n    def check_update(\n        self, update: object\n    ) -> Optional[Union[bool, Tuple[List[str], Optional[Union[bool, FilterDataDict]]]]]:\n        \"\"\"Determines whether an update should be passed to this handler's :attr:`callback`.\n\n        Args:\n            update (:class:`telegram.Update` | :obj:`object`): Incoming update.\n\n        Returns:\n            :obj:`list`: The list of args for the handler.\n\n        \"\"\"\n        if isinstance(update, Update) and update.effective_message:\n            message = update.effective_message\n\n            if (\n                message.entities\n                and message.entities[0].type == MessageEntity.BOT_COMMAND\n                and message.entities[0].offset == 0\n                and message.text\n                and message.get_bot()\n            ):\n                command = message.text[1 : message.entities[0].length]\n                args = message.text.split()[1:]\n                command_parts = command.split(\"@\")\n                command_parts.append(message.get_bot().username)\n\n                if not (\n                    command_parts[0].lower() in self.commands\n                    and command_parts[1].lower() == message.get_bot().username.lower()\n                ):\n                    return None\n\n                if not self._check_correct_args(args):\n                    return None\n\n                filter_result = self.filters.check_update(update)\n                if filter_result:\n                    return args, filter_result\n                return False\n        return None\n\n    def collect_additional_context(\n        self,\n        context: CCT,\n        update: Update,  # skipcq: BAN-B301\n        application: \"Application[Any, CCT, Any, Any, Any, Any]\",  # skipcq: BAN-B301\n        check_result: Optional[Union[bool, Tuple[List[str], Optional[bool]]]],\n    ) -> None:\n        \"\"\"Add text after the command to :attr:`CallbackContext.args` as list, split on single\n        whitespaces and add output of data filters to :attr:`CallbackContext` as well.\n        \"\"\"\n        if isinstance(check_result, tuple):\n            context.args = check_result[0]\n            if isinstance(check_result[1], dict):\n                context.update(check_result[1])\n", "path": "telegram/ext/_commandhandler.py"}]}