Skip to content

Commit

Permalink
lint fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
nzlosh committed Sep 13, 2023
1 parent b3fa5f8 commit 4a69af6
Show file tree
Hide file tree
Showing 6 changed files with 40 additions and 119 deletions.
8 changes: 2 additions & 6 deletions src/slackv3/markdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,15 @@
from markdown.extensions.extra import ExtraExtension
from markdown.preprocessors import Preprocessor

MARKDOWN_LINK_REGEX = re.compile(
r"(?<!!)\[(?P<text>[^\]]+?)\]\((?P<uri>[a-zA-Z0-9]+?:\S+?)\)"
)
MARKDOWN_LINK_REGEX = re.compile(r"(?<!!)\[(?P<text>[^\]]+?)\]\((?P<uri>[a-zA-Z0-9]+?:\S+?)\)")


def slack_markdown_converter(compact_output=False):
"""
This is a Markdown converter for use with Slack.
"""
enable_format("imtext", IMTEXT_CHRS, borders=not compact_output)
md = Markdown(
output_format="imtext", extensions=[ExtraExtension(), AnsiExtension()]
)
md = Markdown(output_format="imtext", extensions=[ExtraExtension(), AnsiExtension()])
md.preprocessors.register(LinkPreProcessor(md), "LinkPreProcessor", 30)
md.stripTopLevelTags = False
return md
Expand Down
14 changes: 4 additions & 10 deletions src/slackv3/person.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,12 @@ class SlackPerson(Person):
def __init__(self, webclient: WebClient, userid=None, channelid=None):
if userid is not None and userid[0] not in ("U", "W", "B"):
raise Exception(
f"This is not a Slack user or bot id: {userid} "
"(should start with B, U or W)"
f"This is not a Slack user or bot id: {userid} " "(should start with B, U or W)"
)

if channelid is not None and channelid[0] not in ("D", "C", "G"):
raise Exception(
f"This is not a valid Slack channelid: {channelid} "
"(should start with D, C or G)"
f"This is not a valid Slack channelid: {channelid} " "(should start with D, C or G)"
)

self._userid = userid
Expand Down Expand Up @@ -95,17 +93,13 @@ def _cache_user_info(self):
res = self._webclient.users_info(user=self._userid)

if res["ok"] is False:
log.error(
f"Cannot find user with ID {self._userid}. Slack Error: {res['error']}"
)
log.error(f"Cannot find user with ID {self._userid}. Slack Error: {res['error']}")
else:
if "bot" in res:
self._user_info["display_name"] = res["bot"].get("name", "")
else:
for attribute in ["real_name", "display_name", "email"]:
self._user_info[attribute] = res["user"]["profile"].get(
attribute, ""
)
self._user_info[attribute] = res["user"]["profile"].get(attribute, "")

team_res = self._webclient.team_info(team=res["user"]["team_id"])
if team_res["ok"]:
Expand Down
11 changes: 3 additions & 8 deletions src/slackv3/room.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,9 +163,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 @@ -240,9 +238,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 @@ -253,8 +249,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
80 changes: 20 additions & 60 deletions src/slackv3/slackv3.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,9 +145,7 @@ def _register_identifiers_pickling(self):
"""
SlackBackend.__build_identifier = self.build_identifier
for cls in (SlackPerson, SlackRoomOccupant, SlackRoom):
copyreg.pickle(
cls, SlackBackend._pickle_identifier, SlackBackend._unpickle_identifier
)
copyreg.pickle(cls, SlackBackend._pickle_identifier, SlackBackend._unpickle_identifier)

def update_alternate_prefixes(self):
"""Converts BOT_ALT_PREFIXES to use the slack ID instead of name
Expand All @@ -170,9 +168,7 @@ def update_alternate_prefixes(self):
f'Failed to look up Slack userid for alternate prefix "{prefix}": {str(e)}'
)

self.bot_alt_prefixes = tuple(
x.lower() for x in self.bot_config.BOT_ALT_PREFIXES
)
self.bot_alt_prefixes = tuple(x.lower() for x in self.bot_config.BOT_ALT_PREFIXES)
log.debug(f"Converted bot_alt_prefixes: {self.bot_config.BOT_ALT_PREFIXES}")

def _setup_event_callbacks(self):
Expand Down Expand Up @@ -370,9 +366,7 @@ def _generic_wrapper(self, event_data):
except KeyError:
log.debug("Ignoring unsupported Slack event!")

def _sm_generic_event_handler(
self, client: SocketModeClient, req: SocketModeRequest
):
def _sm_generic_event_handler(self, client: SocketModeClient, req: SocketModeRequest):
log.debug(
f"Event type: {req.type}\n"
f"Envelope ID: {req.envelope_id}\n"
Expand All @@ -381,9 +375,7 @@ def _sm_generic_event_handler(
f"Retry Reason: {req.retry_reason}\n"
)
# Acknowledge the request
client.send_socket_mode_response(
SocketModeResponse(envelope_id=req.envelope_id)
)
client.send_socket_mode_response(SocketModeResponse(envelope_id=req.envelope_id))
# Dispatch event to the Event API generic event handler.
self._generic_wrapper(req.payload)

Expand All @@ -394,9 +386,7 @@ def _sm_handle_hello(self, *args):
log.debug(f"message listeners : {sm_client.message_listeners}")
if event["type"] == "hello":
self.connect_callback()
self.callback_presence(
Presence(identifier=self.bot_identifier, status=ONLINE)
)
self.callback_presence(Presence(identifier=self.bot_identifier, status=ONLINE))
# Stop calling hello handler for future events.
sm_client.message_listeners.remove(self._sm_handle_hello)
log.info("Unregistered 'hello' handler from socket-mode client")
Expand Down Expand Up @@ -607,9 +597,7 @@ def username_to_userid(self, name: str):
if len(user_ids) == 0:
raise UserDoesNotExistError(f"Cannot find user '{username}'.")
if len(user_ids) > 1:
raise UserNotUniqueError(
f"'{username}' isn't unique: {len(user_ids)} matches found."
)
raise UserNotUniqueError(f"'{username}' isn't unique: {len(user_ids)} matches found.")
return user_ids[0]

@lru_cache(1024)
Expand Down Expand Up @@ -645,14 +633,10 @@ def channels(
References:
- https://slack.com/api/conversations.list
"""
response = self.slack_web.conversations_list(
exclude_archived=exclude_archived, types=types
)
response = self.slack_web.conversations_list(exclude_archived=exclude_archived, types=types)

channels = [
channel
for channel in response["channels"]
if channel["is_member"] or not joined_only
channel for channel in response["channels"] if channel["is_member"] or not joined_only
]

return channels
Expand All @@ -679,17 +663,13 @@ def _prepare_message(self, msg): # or card
if msg.is_group:
to_channel_id = msg.to.id
to_humanreadable = (
msg.to.name
if msg.to.name
else self.channelid_to_channelname(to_channel_id)
msg.to.name if msg.to.name else self.channelid_to_channelname(to_channel_id)
)
else:
to_humanreadable = msg.to.username
to_channel_id = msg.to.channelid
if to_channel_id.startswith("C"):
log.debug(
"This is a divert to private message, sending it directly to the user."
)
log.debug("This is a divert to private message, sending it directly to the user.")
to_channel_id = self.get_im_channel(msg.to.userid)
return to_humanreadable, to_channel_id

Expand All @@ -712,9 +692,7 @@ def send_message(self, msg) -> Message:
if msg.is_group:
to_channel_id = msg.to.id
to_humanreadable = (
msg.to.name
if msg.to.name
else self.channelid_to_channelname(to_channel_id)
msg.to.name if msg.to.name else self.channelid_to_channelname(to_channel_id)
)
else:
to_humanreadable = msg.to.username
Expand All @@ -729,9 +707,7 @@ def send_message(self, msg) -> Message:
to_channel_id = msg.to.channelid

msgtype = "direct" if msg.is_direct else "channel"
log.debug(
f"Sending {msgtype} message to {to_humanreadable} ({to_channel_id})."
)
log.debug(f"Sending {msgtype} message to {to_humanreadable} ({to_channel_id}).")
body = self.md.convert(msg.body)
log.debug(f"Message size: {len(body)}.")

Expand Down Expand Up @@ -823,9 +799,7 @@ def _slack_upload(self, stream: Stream) -> None:
else:
stream.error()
except Exception:
log.exception(
f"Upload of {stream.name} to {stream.identifier.channelname} failed."
)
log.exception(f"Upload of {stream.name} to {stream.identifier.channelname} failed.")

def send_stream_request(
self,
Expand Down Expand Up @@ -871,14 +845,11 @@ def send_card(self, card: Card):
attachment["thumb_url"] = card.thumbnail

if card.color:
attachment["color"] = (
COLORS[card.color] if card.color in COLORS else card.color
)
attachment["color"] = COLORS[card.color] if card.color in COLORS else card.color

if card.fields:
attachment["fields"] = [
{"title": key, "value": value, "short": True}
for key, value in card.fields
{"title": key, "value": value, "short": True} for key, value in card.fields
]

parts = self.prepare_message_body(card.body, self.message_size_limit)
Expand Down Expand Up @@ -917,9 +888,7 @@ def __hash__(self):
return 0 # this is a singleton anyway

def change_presence(self, status: str = ONLINE, message: str = "") -> None:
self.slack_web.users_setPresence(
presence="auto" if status == ONLINE else "away"
)
self.slack_web.users_setPresence(presence="auto" if status == ONLINE else "away")

@staticmethod
def prepare_message_body(body, size_limit):
Expand Down Expand Up @@ -996,9 +965,7 @@ def extract_identifiers_from_string(text):
"Unparseable Slack ID, should start with U, B, C, G, D or W (got `%s`)"
)
if text[1] not in ("@", "#"):
raise ValueError(
f"Expected '@' or '#' Slack ID prefix but got '{text[1]}'."
)
raise ValueError(f"Expected '@' or '#' Slack ID prefix but got '{text[1]}'.")
text = text[2:-1]
if text == "":
raise ValueError(exception_message % "")
Expand Down Expand Up @@ -1034,9 +1001,7 @@ def build_identifier(self, txtrep):
:func:`~extract_identifiers_from_string`.
"""
log.debug(f"Building an identifier from {txtrep}.")
username, userid, channelname, channelid = self.extract_identifiers_from_string(
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)
Expand Down Expand Up @@ -1148,9 +1113,7 @@ def query_room(self, room):

m = SLACK_CLIENT_CHANNEL_HYPERLINK.match(room)
if m is not None:
return SlackRoom(
webclient=self.slack_web, channelid=m.groupdict()["id"], bot=self
)
return SlackRoom(webclient=self.slack_web, channelid=m.groupdict()["id"], bot=self)

return SlackRoom(webclient=self.slack_web, name=room, bot=self)

Expand Down Expand Up @@ -1204,10 +1167,7 @@ def process_mentions(self, text):
try:
identifier = self.build_identifier(word)
except Exception as e:
log.debug(
f"Tried to build an identifier from '{word}' "
f"but got exception: {e}"
)
log.debug(f"Tried to build an identifier from '{word}' " f"but got exception: {e}")
continue

# We track mentions of persons and rooms.
Expand Down
17 changes: 4 additions & 13 deletions tests/person_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@


class SlackPersonTests(unittest.TestCase):

USER_INFO_OK = json.loads(
"""
{
Expand Down Expand Up @@ -182,14 +181,10 @@ class SlackPersonTests(unittest.TestCase):
def setUp(self):
self.webclient = MagicMock()
self.webclient.users_info.return_value = SlackPersonTests.USER_INFO_OK
self.webclient.conversations_info.return_value = (
SlackPersonTests.CHANNEL_INFO_PUBLIC_OK
)
self.webclient.conversations_info.return_value = SlackPersonTests.CHANNEL_INFO_PUBLIC_OK
self.userid = "W012A3CDE"
self.channelid = "C012AB3CD"
self.p = SlackPerson(
self.webclient, userid=self.userid, channelid=self.channelid
)
self.p = SlackPerson(self.webclient, userid=self.userid, channelid=self.channelid)

def test_wrong_userid(self):
with self.assertRaises(Exception):
Expand Down Expand Up @@ -246,9 +241,7 @@ def test_channelname(self):
self.webclient.conversations_info.assert_called_once_with(channel="C012AB3CD")

def test_channelname_channel_not_found(self):
self.webclient.conversations_info.return_value = (
SlackPersonTests.CHANNEL_INFO_FAIL
)
self.webclient.conversations_info.return_value = SlackPersonTests.CHANNEL_INFO_FAIL
with self.assertRaises(RoomDoesNotExistError) as e:
self.p = SlackPerson(self.webclient, channelid="C012AB3CD")
self.p.channelname
Expand All @@ -270,9 +263,7 @@ def test_to_string(self):
self.assertEqual(str(self.p), "<@W012A3CDE>")

def test_equal(self):
self.another_p = SlackPerson(
self.webclient, userid=self.userid, channelid=self.channelid
)
self.another_p = SlackPerson(self.webclient, userid=self.userid, channelid=self.channelid)
self.assertTrue(self.p == self.another_p)
self.assertFalse(self.p == "this is not a person")

Expand Down
Loading

0 comments on commit 4a69af6

Please sign in to comment.