Skip to content

Commit df65f62

Browse files
committed
CQHandler, Persistence, Tests
1 parent 4e932ab commit df65f62

11 files changed

+266
-51
lines changed

telegram/bot.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,7 @@ def __init__(
227227
self.defaults = defaults
228228

229229
# set up callback_data
230-
if isinstance(arbitrary_callback_data, int) or arbitrary_callback_data is None:
230+
if not isinstance(arbitrary_callback_data, bool) or arbitrary_callback_data is None:
231231
maxsize = cast(Union[int, None], arbitrary_callback_data)
232232
self.arbitrary_callback_data = True
233233
else:
@@ -239,7 +239,7 @@ def __init__(
239239
if self.arbitrary_callback_data and not self.validate_callback_data:
240240
warnings.warn(
241241
"If 'validate_callback_data' is False, incoming callback data wont be"
242-
"validated. Use only if you revoked your bot token and set to true"
242+
"validated. Use only if you revoked your bot token and set to True"
243243
"after a few days."
244244
)
245245

telegram/ext/basepersistence.py

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424

2525
from telegram import Bot
2626

27-
from telegram.utils.types import ConversationDict, CCDData
27+
from telegram.utils.types import ConversationDict, CDCData
2828

2929

3030
class BasePersistence(ABC):
@@ -86,9 +86,11 @@ def __new__(cls, *args: Any, **kwargs: Any) -> 'BasePersistence': # pylint: dis
8686
get_user_data = instance.get_user_data
8787
get_chat_data = instance.get_chat_data
8888
get_bot_data = instance.get_bot_data
89+
get_callback_data = instance.get_callback_data
8990
update_user_data = instance.update_user_data
9091
update_chat_data = instance.update_chat_data
9192
update_bot_data = instance.update_bot_data
93+
update_callback_data = instance.update_callback_data
9294

9395
def get_user_data_insert_bot() -> DefaultDict[int, Dict[Any, Any]]:
9496
return instance.insert_bot(get_user_data())
@@ -99,6 +101,12 @@ def get_chat_data_insert_bot() -> DefaultDict[int, Dict[Any, Any]]:
99101
def get_bot_data_insert_bot() -> Dict[Any, Any]:
100102
return instance.insert_bot(get_bot_data())
101103

104+
def get_callback_data_insert_bot() -> Optional[CDCData]:
105+
cdc_data = get_callback_data()
106+
if cdc_data is None:
107+
return None
108+
return cdc_data[0], instance.insert_bot(cdc_data[1]), cdc_data[2]
109+
102110
def update_user_data_replace_bot(user_id: int, data: Dict) -> None:
103111
return update_user_data(user_id, instance.replace_bot(data))
104112

@@ -108,12 +116,18 @@ def update_chat_data_replace_bot(chat_id: int, data: Dict) -> None:
108116
def update_bot_data_replace_bot(data: Dict) -> None:
109117
return update_bot_data(instance.replace_bot(data))
110118

119+
def update_callback_data_replace_bot(data: CDCData) -> None:
120+
maxsize, obj_data, queue = data
121+
return update_callback_data((maxsize, instance.replace_bot(obj_data), queue))
122+
111123
instance.get_user_data = get_user_data_insert_bot
112124
instance.get_chat_data = get_chat_data_insert_bot
113125
instance.get_bot_data = get_bot_data_insert_bot
126+
instance.get_callback_data = get_callback_data_insert_bot
114127
instance.update_user_data = update_user_data_replace_bot
115128
instance.update_chat_data = update_chat_data_replace_bot
116129
instance.update_bot_data = update_bot_data_replace_bot
130+
instance.update_callback_data = update_callback_data_replace_bot
117131
return instance
118132

119133
def __init__(
@@ -325,12 +339,12 @@ def get_bot_data(self) -> Dict[Any, Any]:
325339
:obj:`dict`: The restored bot data.
326340
"""
327341

328-
def get_callback_data(self) -> Optional[CCDData]:
342+
def get_callback_data(self) -> Optional[CDCData]:
329343
"""Will be called by :class:`telegram.ext.Dispatcher` upon creation with a
330344
persistence object. If callback data was stored, it should be returned.
331345
332346
Returns:
333-
Optional[:class:`telegram.utils.types.CCDData`:]: The restored meta data as three-tuple
347+
Optional[:class:`telegram.utils.types.CDCData`:]: The restored meta data as three-tuple
334348
of :obj:`int`, dictionary and :class:`collections.deque` or :obj:`None`, if no data
335349
was stored.
336350
"""
@@ -392,12 +406,12 @@ def update_bot_data(self, data: Dict) -> None:
392406
data (:obj:`dict`): The :attr:`telegram.ext.dispatcher.bot_data` .
393407
"""
394408

395-
def update_callback_data(self, data: CCDData) -> None:
409+
def update_callback_data(self, data: CDCData) -> None:
396410
"""Will be called by the :class:`telegram.ext.Dispatcher` after a handler has
397411
handled an update.
398412
399413
Args:
400-
data (:class:`telegram.utils.types.CCDData`:): The relevant data to restore
414+
data (:class:`telegram.utils.types.CDCData`:): The relevant data to restore
401415
:attr:`telegram.ext.dispatcher.bot.callback_data`.
402416
"""
403417
raise NotImplementedError

telegram/ext/callbackqueryhandler.py

Lines changed: 23 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -80,13 +80,18 @@ class CallbackQueryHandler(Handler[Update]):
8080
:class:`telegram.ext.JobQueue` instance created by the :class:`telegram.ext.Updater`
8181
which can be used to schedule new jobs. Default is :obj:`False`.
8282
DEPRECATED: Please switch to context based callbacks.
83-
pattern (:obj:`str` | `Pattern` | :obj:`callable`, optional): Regex pattern. If not
84-
:obj:`None`, and :attr:`pattern` is a string or regex pattern, ``re.match`` is used on
85-
:attr:`telegram.CallbackQuery.data` to determine if an update should be handled by this
86-
handler. If the data is no string, the update won't be handled in this case. If
87-
:attr:`pattern` is a callable, it must accept exactly one argument, being
88-
:attr:`telegram.CallbackQuery.data`. It must return :obj:`True`, :obj:`Fales` or
89-
:obj:`None` to indicate, whether the update should be handled.
83+
pattern (:obj:`str` | `Pattern` | :obj:`callable` | :obj:`type`, optional):
84+
Pattern to test :attr:`telegram.CallbackQuery.data` against. If a string or a regex
85+
pattern is passed, :meth:`re.match` is used on :attr:`telegram.CallbackQuery.data` to
86+
determine if an update should be handled by this handler. If your bot allows arbitrary
87+
objects as ``callback_data``, non-strings will not be accepted. To filter arbitrary
88+
objects you may pass
89+
90+
* a callable, accepting exactly one argument, namely the
91+
:attr:`telegram.CallbackQuery.data`. It must return :obj:`True`, :obj:`False` or
92+
:obj:`None` to indicate, whether the update should be handled.
93+
* a :obj:`type`. If :attr:`telegram.CallbackQuery.data` is an instance of that type
94+
(or a subclass), the update will be handled.
9095
pass_groups (:obj:`bool`, optional): If the callback should be passed the result of
9196
``re.match(pattern, data).groups()`` as a keyword argument called ``groups``.
9297
Default is :obj:`False`
@@ -110,8 +115,8 @@ class CallbackQueryHandler(Handler[Update]):
110115
passed to the callback function.
111116
pass_job_queue (:obj:`bool`): Determines whether ``job_queue`` will be passed to
112117
the callback function.
113-
pattern (:obj:`str` | `Pattern`): Optional. Regex pattern to test
114-
:attr:`telegram.CallbackQuery.data` against.
118+
pattern (`Pattern` | :obj:`callable` | :obj:`type`): Optional. Regex pattern, callback or
119+
type to test :attr:`telegram.CallbackQuery.data` against.
115120
pass_groups (:obj:`bool`): Determines whether ``groups`` will be passed to the
116121
callback function.
117122
pass_groupdict (:obj:`bool`): Determines whether ``groupdict``. will be passed to
@@ -129,7 +134,7 @@ def __init__(
129134
callback: Callable[[Update, 'CallbackContext'], RT],
130135
pass_update_queue: bool = False,
131136
pass_job_queue: bool = False,
132-
pattern: Union[str, Pattern] = None,
137+
pattern: Union[str, Pattern, type, Callable[[Any], Optional[bool]]] = None,
133138
pass_groups: bool = False,
134139
pass_groupdict: bool = False,
135140
pass_user_data: bool = False,
@@ -164,14 +169,14 @@ def check_update(self, update: Any) -> Optional[Union[bool, object]]:
164169
"""
165170
if isinstance(update, Update) and update.callback_query:
166171
callback_data = update.callback_query.data
167-
if self.pattern:
168-
if callback_data is not None:
169-
if callable(self.pattern):
170-
return self.pattern(callback_data)
171-
if isinstance(callback_data, str):
172-
match = re.match(self.pattern, callback_data)
173-
if match:
174-
return match
172+
if self.pattern and callback_data is not None:
173+
if isinstance(self.pattern, type):
174+
return isinstance(callback_data, self.pattern)
175+
if callable(self.pattern):
176+
return self.pattern(callback_data)
177+
match = re.match(self.pattern, callback_data)
178+
if match:
179+
return match
175180
else:
176181
return True
177182
return None

telegram/ext/dictpersistence.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
encode_conversations_to_json,
2929
)
3030
from telegram.ext import BasePersistence
31-
from telegram.utils.types import ConversationDict, CCDData
31+
from telegram.utils.types import ConversationDict, CDCData
3232

3333
try:
3434
import ujson as json
@@ -193,8 +193,8 @@ def bot_data_json(self) -> str:
193193
return json.dumps(self.bot_data)
194194

195195
@property
196-
def callback_data(self) -> Optional[CCDData]:
197-
""":class:`telegram.utils.types.CCDData`: The meta data on the stored callback data."""
196+
def callback_data(self) -> Optional[CDCData]:
197+
""":class:`telegram.utils.types.CDCData`: The meta data on the stored callback data."""
198198
return self._callback_data
199199

200200
@property
@@ -258,11 +258,11 @@ def get_bot_data(self) -> Dict[Any, Any]:
258258
self._bot_data = {}
259259
return deepcopy(self.bot_data) # type: ignore[arg-type]
260260

261-
def get_callback_data(self) -> Optional[CCDData]:
261+
def get_callback_data(self) -> Optional[CDCData]:
262262
"""Returns the callback_data created from the ``callback_data_json`` or :obj:`None`.
263263
264264
Returns:
265-
Optional[:class:`telegram.utils.types.CCDData`:]: The restored meta data as three-tuple
265+
Optional[:class:`telegram.utils.types.CDCData`:]: The restored meta data as three-tuple
266266
of :obj:`int`, dictionary and :class:`collections.deque` or :obj:`None`, if no data
267267
was stored.
268268
"""
@@ -341,11 +341,11 @@ def update_bot_data(self, data: Dict) -> None:
341341
self._bot_data = data.copy()
342342
self._bot_data_json = None
343343

344-
def update_callback_data(self, data: CCDData) -> None:
344+
def update_callback_data(self, data: CDCData) -> None:
345345
"""Will update the callback_data (if changed).
346346
347347
Args:
348-
data (:class:`telegram.utils.types.CCDData`:): The relevant data to restore
348+
data (:class:`telegram.utils.types.CDCData`:): The relevant data to restore
349349
:attr:`telegram.ext.dispatcher.bot.callback_data`.
350350
"""
351351
if self._callback_data == data:

telegram/ext/picklepersistence.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
from typing import Any, DefaultDict, Dict, Optional, Tuple
2424

2525
from telegram.ext import BasePersistence
26-
from telegram.utils.types import ConversationDict, CCDData
26+
from telegram.utils.types import ConversationDict, CDCData
2727

2828

2929
class PicklePersistence(BasePersistence):
@@ -99,7 +99,7 @@ def __init__(
9999
self.user_data: Optional[DefaultDict[int, Dict]] = None
100100
self.chat_data: Optional[DefaultDict[int, Dict]] = None
101101
self.bot_data: Optional[Dict] = None
102-
self.callback_data: Optional[CCDData] = None
102+
self.callback_data: Optional[CDCData] = None
103103
self.conversations: Optional[Dict[str, Dict[Tuple, Any]]] = None
104104

105105
def load_singlefile(self) -> None:
@@ -210,11 +210,11 @@ def get_bot_data(self) -> Dict[Any, Any]:
210210
self.load_singlefile()
211211
return deepcopy(self.bot_data) # type: ignore[arg-type]
212212

213-
def get_callback_data(self) -> Optional[CCDData]:
213+
def get_callback_data(self) -> Optional[CDCData]:
214214
"""Returns the callback data from the pickle file if it exists or :obj:`None`.
215215
216216
Returns:
217-
Optional[:class:`telegram.utils.types.CCDData`:]: The restored meta data as three-tuple
217+
Optional[:class:`telegram.utils.types.CDCData`:]: The restored meta data as three-tuple
218218
of :obj:`int`, dictionary and :class:`collections.deque` or :obj:`None`, if no data
219219
was stored.
220220
"""
@@ -328,12 +328,12 @@ def update_bot_data(self, data: Dict) -> None:
328328
else:
329329
self.dump_singlefile()
330330

331-
def update_callback_data(self, data: CCDData) -> None:
331+
def update_callback_data(self, data: CDCData) -> None:
332332
"""Will update the callback_data (if changed) and depending on :attr:`on_flush` save the
333333
pickle file.
334334
335335
Args:
336-
data (:class:`telegram.utils.types.CCDData`:): The relevant data to restore
336+
data (:class:`telegram.utils.types.CDCData`:): The relevant data to restore
337337
:attr:`telegram.ext.dispatcher.bot.callback_data`.
338338
"""
339339
if self.callback_data == data:

telegram/utils/callbackdatacache.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
from uuid import uuid4
2727

2828
from telegram.utils.helpers import to_float_timestamp
29-
from telegram.utils.types import CCDData
29+
from telegram.utils.types import CDCData
3030

3131

3232
class CallbackDataCache:
@@ -75,15 +75,15 @@ def __init__(
7575
self.__lock = Lock()
7676

7777
@property
78-
def persistence_data(self) -> CCDData:
78+
def persistence_data(self) -> CDCData:
7979
"""
8080
The data that needs to be persistence to allow caching callback data across bot reboots.
8181
A new instance of this class can be created by::
8282
8383
CallbackDataCache(*callback_data_cache.persistence_data)
8484
8585
Returns:
86-
:class:`telegram.utils.types.CCDData`: The internal data as expected by
86+
:class:`telegram.utils.types.CDCData`: The internal data as expected by
8787
:meth:`telegram.ext.BasePersistence.update_callback_data`.
8888
"""
8989
with self.__lock:

telegram/utils/types.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@
4040
SLT = Union[RT, List[RT], Tuple[RT, ...]]
4141
"""Single instance or list/tuple of instances."""
4242

43-
CCDData = Tuple[Optional[int], Dict[str, Tuple[float, Any]], Deque[str]]
43+
CDCData = Tuple[Optional[int], Dict[str, Tuple[float, Any]], Deque[str]]
4444
"""
4545
Tuple[Optional[:obj:`int`], Dict[:obj:`str`, Tuple[:obj:`float`, :obj:`Any`]], Deque[:obj:`str`]]:
4646
Data returned by :attr:`telegram.utils.callbackdatacache.CallbackDataCache.persistence_data`.

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy