Skip to content
This repository has been archived by the owner on Jun 18, 2024. It is now read-only.

Commit

Permalink
Merge pull request #92 from ltworf/cache_im
Browse files Browse the repository at this point in the history
Cache im
  • Loading branch information
ltworf authored Aug 20, 2018
2 parents 032eea1 + ea81010 commit 19e96e4
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 20 deletions.
1 change: 1 addition & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
* Improved debian packaging
* Force correct IRC nickname
* Send files
* Faster query message send

1.0
* Initial release
1 change: 0 additions & 1 deletion irc.py
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,6 @@ def _message(self, sl_ev: Union[slack.Message, slack.MessageDelete, slack.Messag
)

def slack_event(self, sl_ev):
#TODO handle p2p messages
if isinstance(sl_ev, slack.MessageDelete):
self._message(sl_ev, '[deleted]')
elif isinstance(sl_ev, slack.Message):
Expand Down
52 changes: 33 additions & 19 deletions slack.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,7 @@ def __init__(self, tokenfile: str) -> None:
self.client = SlackClient(token)
self._usercache = {} # type: Dict[str, User]
self._usermapcache = {} # type: Dict[str, User]
self._imcache = {} # type: Dict[str, str]

def away(self, is_away: bool) -> None:
"""
Expand Down Expand Up @@ -396,28 +397,41 @@ def send_message(self, channel_id: str, msg: str) -> None:
raise ResponseException(response)

def send_message_to_user(self, user_id: str, msg: str):
"""
Send a message to a user, pass the user id
"""

# Find the channel id
found = False
for i in self.get_ims():
if i.user == user_id:
channel_id = i.id
found = True
break
# 1 to 1 chats are like channels, but use a dedicated API,
# so to deliver a message to them, a channel id is required.
# Those are called IM.

# A conversation does not exist, create one
if not found:
r = self.client.api_call(
"im.open",
return_im=True,
user=user_id,
)
response = load(r, Response)
if not response.ok:
raise ResponseException(response)
channel_id = r['channel']['id']
self.send_message(channel_id, msg)
if user_id in self._imcache:
# channel id is cached
channel_id = self._imcache[user_id]
else:
# Find the channel id
found = False
# Iterate over all the existing conversations
for i in self.get_ims():
if i.user == user_id:
channel_id = i.id
found = True
break
# A conversation does not exist, create one
if not found:
r = self.client.api_call(
"im.open",
return_im=True,
user=user_id,
)
response = load(r, Response)
if not response.ok:
raise ResponseException(response)
channel_id = r['channel']['id']

self._imcache[user_id] = channel_id

self.send_message(channel_id, msg)

def events_iter(self) -> Iterator[Optional[SlackEvent]]:
"""
Expand Down

0 comments on commit 19e96e4

Please sign in to comment.