Skip to content

Commit c17a8be

Browse files
committed
Introduce cachetools
1 parent e92f3b8 commit c17a8be

File tree

7 files changed

+206
-265
lines changed

7 files changed

+206
-265
lines changed

requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,4 @@ cryptography
44
decorator>=4.4.0
55
APScheduler==3.6.3
66
pytz>=2018.6
7+
cachetools==4.2.0

telegram/ext/bot.py

Lines changed: 7 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -49,17 +49,11 @@ class Bot(telegram.bot.Bot):
4949
Args:
5050
defaults (:class:`telegram.ext.Defaults`, optional): An object containing default values to
5151
be used if not set explicitly in the bot methods.
52-
arbitrary_callback_data (:obj:`bool` | :obj:`int` | :obj:`None`, optional): Whether to
52+
arbitrary_callback_data (:obj:`bool` | :obj:`int`, optional): Whether to
5353
allow arbitrary objects as callback data for :class:`telegram.InlineKeyboardButton`.
54-
Pass an integer to specify the maximum number objects cached in memory. Pass 0 or
55-
:obj:`None` for unlimited cache size. Cache limit defaults to 1024. For more info,
54+
Pass an integer to specify the maximum number objects cached in memory. For more info,
5655
please see our wiki. Defaults to :obj:`False`.
5756
58-
Warning:
59-
Not limiting :attr:`maxsize` may cause memory issues for long running bots. If you
60-
don't limit the size, you should be sure that every inline button is actually
61-
pressed or that you manually clear the cache.
62-
6357
"""
6458

6559
def __init__(
@@ -71,7 +65,7 @@ def __init__(
7165
private_key: bytes = None,
7266
private_key_password: bytes = None,
7367
defaults: Defaults = None,
74-
arbitrary_callback_data: Union[bool, int, None] = False,
68+
arbitrary_callback_data: Union[bool, int] = False,
7569
):
7670
super().__init__(
7771
token=token,
@@ -84,8 +78,8 @@ def __init__(
8478
)
8579

8680
# set up callback_data
87-
if not isinstance(arbitrary_callback_data, bool) or arbitrary_callback_data is None:
88-
maxsize = cast(Union[int, None], arbitrary_callback_data)
81+
if not isinstance(arbitrary_callback_data, bool):
82+
maxsize = cast(int, arbitrary_callback_data)
8983
self.arbitrary_callback_data = True
9084
else:
9185
maxsize = 1024
@@ -145,26 +139,8 @@ def get_updates(
145139
)
146140

147141
for update in updates:
148-
if not update.callback_query:
149-
continue
150-
151-
callback_query = update.callback_query
152-
# Get the cached callback data for the CallbackQuery
153-
if callback_query.data:
154-
callback_query.data = self.callback_data.get_button_data( # type: ignore
155-
callback_query.data, update=True
156-
)
157-
# Get the cached callback data for the inline keyboard attached to the
158-
# CallbackQuery
159-
if callback_query.message and callback_query.message.reply_markup:
160-
for row in callback_query.message.reply_markup.inline_keyboard:
161-
for button in row:
162-
if button.callback_data:
163-
button.callback_data = self.callback_data.get_button_data(
164-
# No need to update again, this was already done above
165-
button.callback_data,
166-
update=False,
167-
)
142+
if update.callback_query:
143+
self.callback_data.process_callback_query(update.callback_query)
168144

169145
return updates
170146

telegram/ext/callbackcontext.py

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,8 @@
2121
from queue import Queue
2222
from typing import TYPE_CHECKING, Any, Dict, List, Match, NoReturn, Optional, Tuple, Union
2323

24-
from telegram import Update
24+
from telegram import Update, CallbackQuery
2525
from telegram.ext import Bot as ExtBot
26-
from telegram.ext.utils.callbackdatacache import CallbackDataCache
2726

2827
if TYPE_CHECKING:
2928
from telegram import Bot
@@ -144,16 +143,31 @@ def user_data(self, value: Any) -> NoReturn:
144143
"You can not assign a new value to user_data, see " "https://git.io/fjxKe"
145144
)
146145

147-
@property
148-
def callback_data_cache(self) -> Optional[CallbackDataCache]:
146+
def drop_callback_data(self, callback_query: CallbackQuery) -> None:
149147
"""
150-
:class:`telegram.utils.callbackdatacache.CallbackDataCache`: Optional. Cache for the bots
151-
callback data. Only present when the bot uses allows to use arbitrary callback data.
152-
Useful for manually dropping unused objects from the cache.
148+
Deletes the cached data for the specified callback query.
149+
150+
Note:
151+
Will *not* raise exceptions in case the data is not found in the cache.
152+
*Will* raise :class:`KeyError` in case the callback query can not be found in the
153+
cache.
154+
155+
Args:
156+
callback_query (:class:`telegram.CallbackQuery`): The callback query.
157+
158+
Raises:
159+
KeyError | RuntimeError: :class:`KeyError`, if the callback query can not be found in
160+
the cache and :class:`RuntimeError`, if the bot doesn't allow for arbitrary
161+
callback data.
153162
"""
154163
if isinstance(self.bot, ExtBot):
155-
return self.bot.callback_data if self.bot.arbitrary_callback_data else None
156-
return None
164+
if not self.bot.arbitrary_callback_data:
165+
RuntimeError(
166+
'This telegram.ext.Bot instance does not use arbitrary callback data.'
167+
)
168+
self.bot.callback_data.drop_data(callback_query)
169+
else:
170+
raise RuntimeError('telegram.Bot does not allow for arbitrary callback data.')
157171

158172
@classmethod
159173
def from_error(

telegram/ext/dispatcher.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -199,13 +199,12 @@ def __init__(
199199
raise ValueError("bot_data must be of type dict")
200200
if self.persistence.store_callback_data:
201201
self.bot = cast(telegram.ext.bot.Bot, self.bot)
202-
callback_data = self.persistence.get_callback_data()
203-
if callback_data is not None:
204-
if not isinstance(callback_data, tuple) and len(callback_data) != 2:
202+
persistent_data = self.persistence.get_callback_data()
203+
if persistent_data is not None:
204+
if not isinstance(persistent_data, tuple) and len(persistent_data) != 2:
205205
raise ValueError('callback_data must be a 2-tuple')
206-
button_data, lru_list = callback_data
207206
self.bot.callback_data = CallbackDataCache(
208-
self.bot.callback_data.maxsize, button_data=button_data, lru_list=lru_list
207+
self.bot.callback_data.maxsize, persistent_data=persistent_data
209208
)
210209
else:
211210
self.persistence = None

telegram/ext/updater.py

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -87,14 +87,8 @@ class Updater:
8787
be used if not set explicitly in the bot methods.
8888
arbitrary_callback_data (:obj:`bool` | :obj:`int` | :obj:`None`, optional): Whether to
8989
allow arbitrary objects as callback data for :class:`telegram.InlineKeyboardButton`.
90-
Pass an integer to specify the maximum number of cached objects. Pass 0 or :obj:`None`
91-
for unlimited cache size. Cache limit defaults to 1024. For more info, please see
92-
our wiki. Defaults to :obj:`False`.
93-
94-
Warning:
95-
Not limiting :attr:`maxsize` may cause memory issues for long running bots. If you
96-
don't limit the size, you should be sure that every inline button is actually
97-
pressed or that you manually clear the cache using e.g. :meth:`clear`.
90+
Pass an integer to specify the maximum number of cached objects. For more info, please
91+
see our wiki. Defaults to :obj:`False`.
9892
9993
Raises:
10094
ValueError: If both :attr:`token` and :attr:`bot` are passed or none of them.

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