Skip to content

Commit 09b4418

Browse files
committed
Add caching for Slack channels in SlackWebMessagingIntegration
- Introduced a channels cache to optimize channel ID retrieval. - Implemented methods to load and refresh the channels cache. - Updated _get_channel_id to utilize the cache, improving performance and reducing API calls.
1 parent 8b5f82e commit 09b4418

File tree

1 file changed

+25
-4
lines changed

1 file changed

+25
-4
lines changed

elementary/messages/messaging_integrations/slack_web.py

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ def __init__(self, client: WebClient, tracking: Optional[Tracking] = None) -> No
4444
self.client = client
4545
self.tracking = tracking
4646
self._email_to_user_id_cache: Dict[str, str] = {}
47+
self._channels_cache: Optional[Dict[str, str]] = None
4748

4849
@classmethod
4950
def from_token(
@@ -143,11 +144,31 @@ def _iter_channels(self, cursor: Optional[str] = None) -> Iterator[dict]:
143144
raise ValueError("Next cursor is not a string")
144145
yield from self._iter_channels(next_cursor)
145146

147+
def _load_channels(self) -> None:
148+
self._channels_cache = {}
149+
try:
150+
for channel in self._iter_channels():
151+
self._channels_cache[channel["name"]] = channel["id"]
152+
logger.debug(f"Loaded {len(self._channels_cache)} channels into cache")
153+
except Exception as e:
154+
logger.error(f"Failed to load channels: {e}")
155+
# Keep cache as empty dict rather than None to avoid retrying constantly
156+
self._channels_cache = {}
157+
158+
def _ensure_channels_loaded(self) -> None:
159+
if self._channels_cache is None:
160+
self._load_channels()
161+
162+
def refresh_channels_cache(self) -> None:
163+
self._load_channels()
164+
146165
def _get_channel_id(self, channel_name: str) -> str:
147-
for channel in self._iter_channels():
148-
if channel["name"] == channel_name:
149-
return channel["id"]
150-
raise MessagingIntegrationError(f"Channel {channel_name} not found")
166+
self._ensure_channels_loaded()
167+
168+
if channel_name not in self._channels_cache:
169+
raise MessagingIntegrationError(f"Channel {channel_name} not found")
170+
171+
return self._channels_cache[channel_name]
151172

152173
def _join_channel(self, channel_id: str) -> None:
153174
try:

0 commit comments

Comments
 (0)