Repository: python-telegram-bot/python-telegram-bot

Issue:
CallbackQueryHandler to support filtering game_short_name
### What kind of feature are you missing? Where do you notice a shortcoming of PTB?

Currently, the CallbackQueryHandler in the library only checks the .data attribute when handling callback queries ([ref](https://github.com/python-telegram-bot/python-telegram-bot/blob/6fc45a803dee783df52a8648664a37d08c0981ec/telegram/ext/_handlers/callbackqueryhandler.py#L143)). This presents a limitation as it doesn't support regex filtering handling clicks on buttons associated with CallbackGame. When a user clicks on a CallbackGame button, the .data attribute is None, causing the CallbackQueryHandler's regex pattern match to fail if it is set.

### Describe the solution you'd like

I think changing this line to 

```python
callback_data = update.callback_query.data or update.callback_query.game_short_name
``` 

would solve this limitation.

### Describe alternatives you've considered

Currently I manage to overcome this by handling all callbacks in one handler without pattern match and then using if else with `.game_short_name` attribute 

### Additional context

_No response_


Discussion:
Hi I rewrote it a bit to make it more clear its about providing filtering, as you wrote in the end of the issue, a handler without a pattern set handles that update just fine.

I am fine with adding a filter attribute for that in the same function as pattern, I don't think changing the behavior of the argument as you describe is the best way, I would rather see a new argument introduced.
Hey. 

> I am fine with adding a filter attribute for that in the same function as pattern, I don't think changing the behavior of the argument as you describe is the best way, I would rather see a new argument introduced.

@Pooolitzer I guess you mean an interface like `CQH(pattern=…, game_patterm=…)` here? then we would the behavior

* `CQH(pattern=None, game_patterm=None)` handles *any* CQ → backward compatible
* `CQH(pattern=pattern, game_patterm=None)` handles only CQs with `.data` → backward compatible
* `CQH(pattern=None, game_patterm=pattern)` handles only CQs with `.game_short_name`. → still backward compatible since `game_pattern defaults to `None`
* `CQH(pattern=pattern, game_patterm=game_pattern)` handles only CQs with matching `.data` xor matching `.game_short_name` → also backward compatible since .data and .game_short_name are mutually exclusive

I vote +0 on this, i.e. I welcome a PR, but don't see a need for the PTB dev team to work on this actively
Hey @Bibo-Joshi, I would like to create a PR for this. 



Patch:
diff --git a/AUTHORS.rst b/AUTHORS.rst
index fe69dba625d..403362aaab0 100644
--- a/AUTHORS.rst
+++ b/AUTHORS.rst
@@ -60,6 +60,7 @@ The following wonderful people contributed directly or indirectly to this projec
 - `Hugo Damer <https://github.com/HakimusGIT>`_
 - `ihoru <https://github.com/ihoru>`_
 - `Iulian Onofrei <https://github.com/revolter>`_
+- `Jainam Oswal <https://github.com/jainamoswal>`_
 - `Jasmin Bom <https://github.com/jsmnbom>`_
 - `JASON0916 <https://github.com/JASON0916>`_
 - `jeffffc <https://github.com/jeffffc>`_
diff --git a/telegram/ext/_handlers/callbackqueryhandler.py b/telegram/ext/_handlers/callbackqueryhandler.py
index afd64887964..c8fb0e7b3f0 100644
--- a/telegram/ext/_handlers/callbackqueryhandler.py
+++ b/telegram/ext/_handlers/callbackqueryhandler.py
@@ -51,6 +51,15 @@ class CallbackQueryHandler(BaseHandler[Update, CCT]):
 
           .. versionadded:: 13.6
 
+        * If neither :paramref:`pattern` nor :paramref:`game_pattern` is set, `any`
+          ``CallbackQuery`` will be handled. If only :paramref:`pattern` is set, queries with
+          :attr:`~telegram.CallbackQuery.game_short_name` will `not` be considered and vice versa.
+          If both patterns are set, queries with either :attr:
+          `~telegram.CallbackQuery.game_short_name` or :attr:`~telegram.CallbackQuery.data`
+          matching the defined pattern will be handled
+
+          .. versionadded:: NEXT.VERSION
+
     Warning:
         When setting :paramref:`block` to :obj:`False`, you cannot rely on adding custom
         attributes to :class:`telegram.ext.CallbackContext`. See its docs for more info.
@@ -85,6 +94,13 @@ async def callback(update: Update, context: CallbackContext)
 
             .. versionchanged:: 13.6
                Added support for arbitrary callback data.
+        game_pattern (:obj:`str` | :func:`re.Pattern <re.compile>` | optional)
+            Pattern to test :attr:`telegram.CallbackQuery.game_short_name` against. If a string or
+            a regex pattern is passed, :func:`re.match` is used on
+            :attr:`telegram.CallbackQuery.game_short_name` to determine if an update should be
+            handled by this handler.
+
+            .. versionadded:: NEXT.VERSION
         block (:obj:`bool`, optional): Determines whether the return value of the callback should
             be awaited before processing the next handler in
             :meth:`telegram.ext.Application.process_update`. Defaults to :obj:`True`.
@@ -98,13 +114,15 @@ async def callback(update: Update, context: CallbackContext)
 
             .. versionchanged:: 13.6
                Added support for arbitrary callback data.
+        game_pattern (:func:`re.Pattern <re.compile>`): Optional.
+            Regex pattern to test :attr:`telegram.CallbackQuery.game_short_name`
         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`.
 
     """
 
-    __slots__ = ("pattern",)
+    __slots__ = ("game_pattern", "pattern")
 
     def __init__(
         self,
@@ -112,6 +130,7 @@ def __init__(
         pattern: Optional[
             Union[str, Pattern[str], type, Callable[[object], Optional[bool]]]
         ] = None,
+        game_pattern: Optional[Union[str, Pattern[str]]] = None,
         block: DVType[bool] = DEFAULT_TRUE,
     ):
         super().__init__(callback, block=block)
@@ -120,13 +139,15 @@ def __init__(
             raise TypeError(
                 "The `pattern` must not be a coroutine function! Use an ordinary function instead."
             )
-
         if isinstance(pattern, str):
             pattern = re.compile(pattern)
 
+        if isinstance(game_pattern, str):
+            game_pattern = re.compile(game_pattern)
         self.pattern: Optional[
             Union[str, Pattern[str], type, Callable[[object], Optional[bool]]]
         ] = pattern
+        self.game_pattern: Optional[Union[str, Pattern[str]]] = game_pattern
 
     def check_update(self, update: object) -> Optional[Union[bool, object]]:
         """Determines whether an update should be passed to this handler's :attr:`callback`.
@@ -139,22 +160,37 @@ def check_update(self, update: object) -> Optional[Union[bool, object]]:
 
         """
         # pylint: disable=too-many-return-statements
-        if isinstance(update, Update) and update.callback_query:
-            callback_data = update.callback_query.data
-            if self.pattern:
-                if callback_data is None:
-                    return False
-                if isinstance(self.pattern, type):
-                    return isinstance(callback_data, self.pattern)
-                if callable(self.pattern):
-                    return self.pattern(callback_data)
-                if not isinstance(callback_data, str):
-                    return False
-                if match := re.match(self.pattern, callback_data):
-                    return match
-            else:
-                return True
-        return None
+        if not (isinstance(update, Update) and update.callback_query):
+            return None
+
+        callback_data = update.callback_query.data
+        game_short_name = update.callback_query.game_short_name
+
+        if not any([self.pattern, self.game_pattern]):
+            return True
+
+        # we check for .data or .game_short_name from update to filter based on whats coming
+        # this gives xor-like behavior
+        if callback_data:
+            if not self.pattern:
+                return False
+            if isinstance(self.pattern, type):
+                return isinstance(callback_data, self.pattern)
+            if callable(self.pattern):
+                return self.pattern(callback_data)
+            if not isinstance(callback_data, str):
+                return False
+            if match := re.match(self.pattern, callback_data):
+                return match
+
+        elif game_short_name:
+            if not self.game_pattern:
+                return False
+            if match := re.match(self.game_pattern, game_short_name):
+                return match
+        else:
+            return True
+        return False
 
     def collect_additional_context(
         self,


Test patch:
diff --git a/tests/ext/test_callbackqueryhandler.py b/tests/ext/test_callbackqueryhandler.py
index 65b5589c041..f96c074d2d1 100644
--- a/tests/ext/test_callbackqueryhandler.py
+++ b/tests/ext/test_callbackqueryhandler.py
@@ -228,3 +228,47 @@ async def pattern():
 
         with pytest.raises(TypeError, match="must not be a coroutine function"):
             CallbackQueryHandler(self.callback, pattern=pattern)
+
+    def test_game_pattern(self, callback_query):
+        callback_query.callback_query.data = None
+
+        callback_query.callback_query.game_short_name = "test data"
+        handler = CallbackQueryHandler(self.callback_basic, game_pattern=".*est.*")
+        assert handler.check_update(callback_query)
+
+        callback_query.callback_query.game_short_name = "nothing here"
+        assert not handler.check_update(callback_query)
+
+        callback_query.callback_query.game_short_name = "this is a short game name"
+        assert not handler.check_update(callback_query)
+
+        callback_query.callback_query.data = "something"
+        handler = CallbackQueryHandler(self.callback_basic, game_pattern="")
+        assert not handler.check_update(callback_query)
+
+    @pytest.mark.parametrize(
+        ("data", "pattern", "game_short_name", "game_pattern", "expected_result"),
+        [
+            (None, None, None, None, True),
+            (None, ".*data", None, None, True),
+            (None, None, None, ".*game", True),
+            (None, ".*data", None, ".*game", True),
+            ("some_data", None, None, None, True),
+            ("some_data", ".*data", None, None, True),
+            ("some_data", None, None, ".*game", False),
+            ("some_data", ".*data", None, ".*game", True),
+            (None, None, "some_game", None, True),
+            (None, ".*data", "some_game", None, False),
+            (None, None, "some_game", ".*game", True),
+            (None, ".*data", "some_game", ".*game", True),
+        ],
+    )
+    def test_pattern_and_game_pattern_interaction(
+        self, callback_query, data, pattern, game_short_name, game_pattern, expected_result
+    ):
+        callback_query.callback_query.data = data
+        callback_query.callback_query.game_short_name = game_short_name
+        handler = CallbackQueryHandler(
+            callback=self.callback, pattern=pattern, game_pattern=game_pattern
+        )
+        assert bool(handler.check_update(callback_query)) == expected_result