Skip to content

Commit

Permalink
Fix channel mentions #57 (#58)
Browse files Browse the repository at this point in the history
* Fix channel mentions (#57)
  • Loading branch information
nzlosh authored Dec 12, 2021
1 parent 16325f4 commit c8518a0
Show file tree
Hide file tree
Showing 5 changed files with 45 additions and 27 deletions.
19 changes: 14 additions & 5 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,24 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
## [0.2.0] Unreleased
### Added
### Changed
### Fixed
### Removed

## [0.1.1] 2021-12-09
### Added
- Documentation for configuring BOT_ADMIN and BOT_ADMIN_NOTIFICATION.
### Changed
### Fixed
- Channel mentions caused messages to be silently dropped. #57 (@nzlosh)
### Removed

## [0.1.0] 2021-11-25
### Added
- Added changelog file.
- Added Github actions for unit tests, codestyle, lint.
- Added Python 3.10 to unit tets
- Added unit tests.
- Added handler for reaction add/remove.
- changelog file.
- Github actions for unit tests, codestyle, lint.
- unit tests.
- Python 3.10 to unit tets
- handler for reaction add/remove events.

### Changed
- Person field returns unique identifier instead of @ usernames which aren't guaranteed to be unique.
Expand Down
23 changes: 16 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,8 @@ Slack Events and Real Time Messaging backend for Errbot

This backend has been developed to support both the Slack Events and Real Time Messaging APIs using the latest SDK from Slack.

The backend has been made available outside the core errbot project to allow development and user
feedback to happen on independent release cycles.
The backend has been made available outside the core errbot project to allow development and user feedback to happen on independent release cycles.

It is the hope and intention of the authors that this backend will eventually be incorporated as part
of the official errbot project.

## Connection Methods

Expand All @@ -30,14 +27,14 @@ The virtual environment is created in `/opt/errbot/virtualenv` and errbot initia

1. Create the errbot virtual environment

```python
```bash
mkdir -p /opt/errbot/backend
virtualenv --python=python3 /opt/errbot/virtualenv
```

2. Install and initialise errbot. [See here for details](https://errbot.readthedocs.io/en/latest/user_guide/setup.html)

```python
```bash
source /opt/errbot/virtualenv/bin/activate
pip install errbot
cd /opt/errbot
Expand All @@ -53,7 +50,7 @@ The virtual environment is created in `/opt/errbot/virtualenv` and errbot initia

4. Clone `err-backend-slackv3` into the backend directory and install module dependencies.

```python
```bash
cd /opt/errbot/backend
git clone https://github.com/errbotio/err-backend-slackv3
pip install -r /opt/errbot/backend/err-backend-slackv3/requirements.txt
Expand Down Expand Up @@ -93,3 +90,15 @@ Ensure the bot is also subscrbed to the following events:
- `message.channels`
- `message.groups`
- `message.im`
Moving from older slack backends
### Bot Admins
Slack changed the way users are uniquely identified from display name `@some_name` to user id `Uxxxxxx`.
Errbot configuration will need to be updated before administrators can be correctly identified aginst
the ACL sets.
The UserID is in plain text format. It can be found in the the Slack full profile page or using the `!whoami` command (`person` field).
Because BOT_ADMINS is defined as plain text User IDs, they can not be used to send notifications. The mention format
`<@Uxxxxx>` must be used in the BOT_ADMINS_NOTIFICATIONS configuration setting for errbot to initiate message to bot administrators.
2 changes: 1 addition & 1 deletion _slack/person.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ def _cache_channel_info(self, refresh=False):
:refresh: Boolean to force fetching channel info even if it was already cached.
"""
if self.channelid is None:
raise ValueError("Unable to lookup and undefined channel id.")
raise ValueError("Unable to lookup an undefined channel id.")

if self._channel_info.get("id") is None or refresh:
res = self._webclient.conversations_info(channel=self.channelid)
Expand Down
18 changes: 9 additions & 9 deletions _slack/room.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def __init__(self, webclient=None, name=None, channelid=None, bot=None):
self._cache_channel_info(channelid)

def __str__(self):
return f"#{self.name}"
return f"<#{self.id}|{self.name}>"

@property
def channelname(self):
Expand Down Expand Up @@ -117,6 +117,11 @@ def id(self):
"""Return the ID of this room"""
return self._cache["id"]

@property
def channelid(self):
"""Return the Slack representation of the channel in the form <#CHANNELID|CHANNELNAME>"""
return f"<#{self.id}|{self.name}>"

@property
def name(self):
"""Return the name of this room"""
Expand Down Expand Up @@ -151,9 +156,7 @@ def create(self, private=False):
try:
if private:
log.info(f"Creating private conversation {self}.")
self._bot.slack_web.conversations_create(
name=self.name, is_private=True
)
self._bot.slack_web.conversations_create(name=self.name, is_private=True)
else:
log.info(f"Creating conversation {self}.")
self._bot.slack_web.conversations_create(name=self.name)
Expand Down Expand Up @@ -225,9 +228,7 @@ def occupants(self):
)
if res["ok"] is True:
for member in res["members"]:
occupants.append(
SlackRoomOccupant(self._webclient, member, self.id, self._bot)
)
occupants.append(SlackRoomOccupant(self._webclient, member, self.id, self._bot))
cursor = res["response_metadata"]["next_cursor"]
else:
log.exception(
Expand All @@ -238,8 +239,7 @@ def occupants(self):

def invite(self, *args):
users = {
user["name"]: user["id"]
for user in self._webclient.api_call("users.list")["members"]
user["name"]: user["id"] for user in self._webclient.api_call("users.list")["members"]
}

for user in args:
Expand Down
10 changes: 5 additions & 5 deletions slackv3.py
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,6 @@ def _rtm_generic_event_handler(client: RTMClient, event: dict):
event_handler = getattr(self, f"_rtm_handle_{event_type}")
return event_handler(client, event)
except AttributeError as e:
log.warning(str(e))
log.debug(f"RTM event type {event_type} not supported.")

log.info("Connecting to Slack RTM API")
Expand Down Expand Up @@ -498,7 +497,6 @@ def _handle_message(self, webclient: WebClient, event):
user = event.get("user", event.get("bot_id"))

text, mentioned = self.process_mentions(text)

text = self.sanitize_uris(text)

log.debug(f"Saw an event: {pprint.pformat(event)}")
Expand Down Expand Up @@ -949,8 +947,9 @@ def build_identifier(self, txtrep):
Supports strings with the formats accepted by
:func:`~extract_identifiers_from_string`.
"""
log.debug(f"building an identifier from {txtrep}.")
log.debug(f"Building an identifier from {txtrep}.")
username, userid, channelname, channelid = self.extract_identifiers_from_string(txtrep)

if userid is None and username is not None:
userid = self.username_to_userid(username)
if channelid is None and channelname is not None:
Expand Down Expand Up @@ -1083,10 +1082,11 @@ def sanitize_uris(text):
<http://example.org|example.org>
<http://example.org>
Returns a plain text representation of the URI.
:returns:
string
"""
text = re.sub(r"<([^|>]+)\|([^|>]+)>", r"\2", text)
text = re.sub(r"<([^#][^|>]+)\|([^|>]+)>", r"\2", text)
text = re.sub(r"<(http([^>]+))>", r"\1", text)

return text
Expand Down Expand Up @@ -1118,6 +1118,6 @@ def process_mentions(self, text):
elif isinstance(identifier, SlackRoom):
log.debug(f"Someone mentioned channel {identifier}")
mentioned.append(identifier)
text = text.replace(word, f"#{identifier.channelid}")
text = text.replace(word, f"{identifier}")

return text, mentioned

0 comments on commit c8518a0

Please sign in to comment.