-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathslackv3.py
1125 lines (989 loc) · 41 KB
/
slackv3.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import copyreg
import json
import logging
import pprint
import re
import sys
import threading
from functools import lru_cache
from typing import BinaryIO
from errbot.backends.base import (
AWAY,
ONLINE,
REACTION_ADDED,
REACTION_REMOVED,
Card,
Identifier,
Message,
Presence,
Reaction,
Room,
RoomDoesNotExistError,
RoomError,
RoomOccupant,
Stream,
UserDoesNotExistError,
UserNotUniqueError,
)
from errbot.core import ErrBot
from errbot.core_plugins import flask_app
from errbot.utils import split_string_after
log = logging.getLogger(__name__)
try:
from slack_sdk.errors import BotUserAccessError, SlackApiError
from slack_sdk.rtm.v2 import RTMClient
from slack_sdk.socket_mode import SocketModeClient
from slack_sdk.socket_mode.request import SocketModeRequest
from slack_sdk.socket_mode.response import SocketModeResponse
from slack_sdk.web import WebClient
from slackeventsapi import SlackEventAdapter
except ImportError:
log.exception("Could not start the SlackSDK backend")
log.fatal(
"You need to install python modules in order to use the Slack backend.\n"
"You can do `pip install errbot[slack-sdk]` to install them."
)
sys.exit(1)
from _slack.lib import USER_IS_BOT_HELPTEXT, SlackAPIResponseError
from _slack.markdown import slack_markdown_converter
from _slack.person import SlackPerson
from _slack.room import SlackRoom, SlackRoomBot, SlackRoomOccupant
# The Slack client automatically turns a channel name into a clickable
# link if you prefix it with a #. Other clients receive this link as a
# token matching this regex.
SLACK_CLIENT_CHANNEL_HYPERLINK = re.compile(r"^<#(?P<id>([CG])[0-9A-Z]+)>$")
USER_IS_BOT_HELPTEXT = (
"Connected to Slack using a bot account, which cannot manage "
"channels itself (you must invite the bot to channels instead, "
"it will auto-accept) nor invite people.\n\n"
"If you need this functionality, you will have to create a "
"regular user account and connect Errbot using that account. "
"For this, you will also need to generate a user token at "
"https://api.slack.com/web."
)
COLORS = {
"red": "#FF0000",
"green": "#008000",
"yellow": "#FFA500",
"blue": "#0000FF",
"white": "#FFFFFF",
"cyan": "#00FFFF",
} # Slack doesn't know its colors
class SlackBackend(ErrBot):
def __init__(self, config):
super().__init__(config)
identity = config.BOT_IDENTITY
self.token = identity.get("token", None)
self.proxies = identity.get("proxies", None)
if not self.token:
log.fatal(
'You need to set your token (found under "Bot Integration" on Slack) in '
"the BOT_IDENTITY setting in your configuration. Without this token I "
"cannot connect to Slack."
)
sys.exit(1)
self.signing_secret = identity.get("signing_secret", None)
self.app_token = identity.get("app_token", None)
# Slack objects will be initialised in the serve_once method.
self.slack_web = None
self.slack_rtm = None
self.slack_events = None
self.slack_socket_mode = None
self.bot_identifier = None
compact = config.COMPACT_OUTPUT if hasattr(config, "COMPACT_OUTPUT") else False
self.md = slack_markdown_converter(compact)
self._register_identifiers_pickling()
def set_message_size_limit(self, limit=4096, hard_limit=40000):
"""
Slack supports upto 40000 characters per message, Errbot maintains 4096 by default.
"""
super().set_message_size_limit(limit, hard_limit)
@staticmethod
def _unpickle_identifier(identifier_str):
return SlackBackend.__build_identifier(identifier_str)
@staticmethod
def _pickle_identifier(identifier):
return SlackBackend._unpickle_identifier, (str(identifier),)
def _register_identifiers_pickling(self):
"""
Register identifiers pickling.
As Slack needs live objects in its identifiers, we need to override their pickling behavior.
But for the unpickling to work we need to use bot.build_identifier, hence the bot parameter here.
But then we also need bot for the unpickling so we save it here at module level.
"""
SlackBackend.__build_identifier = self.build_identifier
for cls in (SlackPerson, SlackRoomOccupant, SlackRoom):
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
Slack only acknowledges direct callouts `@username` in chat if referred
by using the ID of that user.
"""
# convert BOT_ALT_PREFIXES to a list
try:
bot_prefixes = self.bot_config.BOT_ALT_PREFIXES.split(",")
except AttributeError:
bot_prefixes = list(self.bot_config.BOT_ALT_PREFIXES)
converted_prefixes = []
for prefix in bot_prefixes:
try:
converted_prefixes.append(f"<@{self.username_to_userid(prefix)}>")
except Exception as e:
log.error(
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
)
log.debug(f"Converted bot_alt_prefixes: {self.bot_config.BOT_ALT_PREFIXES}")
def _setup_event_callbacks(self):
# List of events obtained from https://api.slack.com/events
slack_event_types = [
"app_home_opened",
"app_mention",
"app_rate_limited",
"app_requested",
"app_uninstalled",
"call_rejected",
"channel_archive",
"channel_created",
"channel_deleted",
"channel_history_changed",
"channel_left",
"channel_rename",
"channel_shared",
"channel_unarchive",
"channel_unshared",
"dnd_updated",
"dnd_updated_user",
"email_domain_changed",
"emoji_changed",
"file_change",
"file_comment_added",
"file_comment_deleted",
"file_comment_edited",
"file_created",
"file_deleted",
"file_public",
"file_shared",
"file_unshared",
"grid_migration_finished",
"grid_migration_started",
"group_archive",
"group_close",
"group_deleted",
"group_history_changed",
"group_left",
"group_open",
"group_rename",
"group_unarchive",
"im_close",
"im_created",
"im_history_changed",
"im_open",
"hello",
"invite_requested",
"link_shared",
"member_joined_channel",
"member_left_channel",
"message",
"message.app_home",
"message.channels",
"message.groups",
"message.im",
"message.mpim",
"pin_added",
"pin_removed",
"reaction_added",
"reaction_removed",
"resources_added",
"resources_removed",
"scope_denied",
"scope_granted",
"star_added",
"star_removed",
"subteam_created",
"subteam_members_changed",
"subteam_self_added",
"subteam_self_removed",
"subteam_updated",
"team_domain_change",
"team_join",
"team_rename",
"tokens_revoked",
"url_verification",
"user_change",
"user_resource_denied",
"user_resource_granted",
"user_resource_removed",
"workflow_step_execute",
]
for t in slack_event_types:
# slacksdk checks for duplicates only when passing a list of callbacks
self.slack_events.on(t, self._generic_wrapper)
self.connect_callback()
def serve_once(self):
self.slack_web = WebClient(token=self.token, proxy=self.proxies)
log.info("Verifying authentication token")
self.auth = self.slack_web.auth_test()
log.debug(f"Auth response: {self.auth}")
if not self.auth["ok"]:
raise SlackAPIResponseError(
error=f"Couldn't authenticate with Slack. Server said: {self.auth['error']}"
)
log.info("Token accepted")
self.bot_identifier = SlackPerson(self.slack_web, self.auth["user_id"])
log.debug(self.bot_identifier)
# Inject bot identity to alternative prefixes
self.update_alternate_prefixes()
# detect legacy and classic bot based on auth_test response (https://api.slack.com/scopes)
if set(
[
"apps",
"bot",
"bot:basic",
"client",
"files:write:user",
"identify",
"post",
"read",
]
).issuperset(self.auth.headers["x-oauth-scopes"].split(",")):
log.info("Using RTM API.")
self.slack_rtm = RTMClient(
token=self.token,
proxy=self.proxies,
auto_reconnect_enabled=True,
)
@self.slack_rtm.on("*")
def _rtm_generic_event_handler(client: RTMClient, event: dict):
"""Calls the rtm event handler based on the event type"""
log.debug("Received rtm event: {}".format(str(event)))
event_type = event["type"]
try:
event_handler = getattr(self, f"_rtm_handle_{event_type}")
return event_handler(client, event)
except AttributeError:
log.warning(f"RTM event type {event_type} not supported.")
log.info("Connecting to Slack RTM API")
self.slack_rtm.start()
else:
# If the Application token is set, run in socket mode otherwise use Request URL.
if self.app_token:
log.info("Using Events API - Socket mode client.")
self.slack_socket_mode = SocketModeClient(
app_token=self.app_token,
web_client=self.slack_web,
on_message_listeners=[self._sm_handle_hello],
)
self.slack_socket_mode.message_listeners.append(self._sm_handle_hello)
self.slack_socket_mode.socket_mode_request_listeners.append(
self._sm_generic_event_handler
)
# TODO: The socket_mode listener will need to gracefully handle disconnections.
self.slack_socket_mode.connect()
else:
log.info("Using Events API - HTTP listener for request URLs.")
if not self.signing_secret:
log.fatal(
'You need to set your signing_secret (found under "Bot Integration" on Slack)'
" in the BOT_IDENTITY setting in your configuration. Without this secret I "
"cannot receive events from Slack."
)
sys.exit(1)
self.slack_events = SlackEventAdapter(
self.signing_secret, "/slack/events", flask_app
)
self._setup_event_callbacks()
try:
log.debug("Initialised, waiting for events.")
# Block here to remain in serve_once().
threading.Event().wait()
except KeyboardInterrupt:
log.info("Interrupt received, shutting down..")
return True
except Exception:
log.exception("Error reading from RTM stream:")
finally:
log.debug("Triggering disconnect callback")
self.disconnect_callback()
def _generic_wrapper(self, event_data):
"""Calls the event handler based on the event type"""
log.debug("Received event: {}".format(str(event_data)))
event = event_data["event"]
event_type = event["type"]
try:
event_handler = getattr(self, f"_handle_{event_type}")
return event_handler(self.slack_web, event)
except AttributeError:
log.warning(f"Event type {event_type} not supported.")
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"
f"Accept Response Payload: {req.accepts_response_payload}\n"
f"Retry Attempt: {req.retry_attempt}\n"
f"Retry Reason: {req.retry_reason}\n"
)
# Acknowledge the request
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)
def _sm_handle_hello(self, *args):
# Workaround socket-mode client calling handler twice with different signatures.
if len(args) == 3:
sm_client, event, raw_event = 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)
)
# 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")
def _rtm_handle_hello(self, client: RTMClient, event: dict):
"""Event handler for the 'hello' event"""
self.slack_web = client.web_client
self.connect_callback()
self.callback_presence(Presence(identifier=self.bot_identifier, status=ONLINE))
def _rtm_handle_goodbye(self, client: RTMClient, event: dict):
"""Handle Slack server's intention to close the connection"""
log.info("Received 'goodbye' from slack server.")
log.debug("Disconnect from Slack RTM API")
self.slack_rtm.disconnect()
self.disconnect_callback()
log.debug("Connect to Slack RTM API")
self.slack_rtm.connect()
def _rtm_handle_message(self, client: RTMClient, event: dict):
self._handle_message(client.web_client, event)
def _rtm_handle_open(self, client: RTMClient, event: dict):
"""Register the bot identity when the RTM connection is established."""
self.bot_identifier = SlackPerson(client.web_client, event["self"]["id"])
def _rtm_handle_presence_change(self, client: RTMClient, event: dict):
"""Event handler for the 'presence_change' event"""
idd = SlackPerson(client.web_client, event["user"])
presence = event["presence"]
# According to https://api.slack.com/docs/presence, presence can
# only be one of 'active' and 'away'
if presence == "active":
status = ONLINE
elif presence == "away":
status = AWAY
else:
log.error(
f"It appears the Slack API changed, I received an unknown presence type {presence}."
)
status = ONLINE
self.callback_presence(Presence(identifier=idd, status=status))
def _rtm_handle_reaction_added(self, client: RTMClient, event: dict):
self._handle_reaction_added(client.web_client, event)
def _rtm_handle_reaction_removed(self, client: RTMClient, event: dict):
self._handle_reaction_removed(client.web_client, event)
def _handle_reaction_added(self, webclient: WebClient, event):
"""Event handler for the 'reaction_added' event"""
emoji = event["reaction"]
log.debug("Added reaction: {}".format(emoji))
def _handle_reaction_removed(self, webclient: WebClient, event):
"""Event handler for the 'reaction_removed' event"""
emoji = event["reaction"]
log.debug("Removed reaction: {}".format(emoji))
def _handle_message(self, webclient: WebClient, event):
"""Event handler for the 'message' event"""
channel = event["channel"]
if channel[0] not in "CGD":
log.warning("Unknown message type! Unable to handle %s", channel)
return
subtype = event.get("subtype", None)
if subtype in ("message_deleted", "channel_topic", "message_replied"):
log.debug("Message of type %s, ignoring this event", subtype)
return
if subtype == "message_changed" and "attachments" in event["message"]:
# If you paste a link into Slack, it does a call-out to grab details
# from it so it can display this in the chatroom. These show up as
# message_changed events with an 'attachments' key in the embedded
# message. We should completely ignore these events otherwise we
# could end up processing bot commands twice (user issues a command
# containing a link, it gets processed, then Slack triggers the
# message_changed event and we end up processing it again as a new
# message. This is not what we want).
log.debug(
"Ignoring message_changed event with attachments, likely caused "
"by Slack auto-expanding a link."
)
return
if "message" in event:
text = event["message"].get("text", "")
user = event["message"].get("user", event.get("bot_id"))
else:
text = event.get("text", "")
user = event.get("user", event.get("bot_id"))
text, mentioned = self.process_mentions(text)
text = self.sanitize_uris(text)
log.debug("Saw an event: %s", pprint.pformat(event))
log.debug("Escaped IDs event text: %s", text)
msg = Message(
text,
extras={
"attachments": event.get("attachments"),
"slack_event": event,
},
)
if channel.startswith("D"):
if subtype == "bot_message":
msg.frm = SlackBot(
webclient,
bot_id=event.get("bot_id"),
bot_username=event.get("username", ""),
)
msg.to = SlackPerson(webclient, user, channel)
else:
if user == self.bot_identifier.userid:
msg.frm = self.bot_identifier
msg.to = self.bot_identifier
else:
msg.frm = SlackPerson(webclient, user, channel)
msg.to = msg.frm
else:
if subtype == "bot_message":
msg.frm = SlackRoomBot(
webclient,
bot_id=event.get("bot_id"),
bot_username=event.get("username", ""),
channelid=channel,
bot=self,
)
msg.to = SlackRoom(webclient=webclient, channelid=channel, bot=self)
else:
if user == self.bot_identifier.userid:
msg.frm = self.bot_identifier
msg.to = self.bot_identifier
else:
msg.to = SlackRoom(webclient=webclient, channelid=channel, bot=self)
msg.frm = SlackRoomOccupant(webclient, user, channel, self)
# TODO: port to slack_sdk
# msg.extras['url'] = f'https://{self.slack_web.server.domain}.slack.com/archives/' \
# f'{channel_link_name}/p{self._ts_for_message(msg).replace(".", "")}'
self.callback_message(msg)
if mentioned:
self.callback_mention(msg, mentioned)
def _rtm_handle_member_joined_channel(self, client: RTMClient, event: dict):
self._handle_member_joined_channel(client.web_client, event)
def _handle_member_joined_channel(self, webclient: WebClient, event):
"""Event handler for the 'member_joined_channel' event"""
user = SlackPerson(webclient, event["user"])
if user == self.bot_identifier:
self.callback_room_joined(
SlackRoom(webclient=webclient, channelid=event["channel"], bot=self)
)
def userid_to_username(self, id_: str):
"""Convert a Slack user ID to their user name"""
user = self.slack_web.users_info(user=id_)["user"]
if user is None:
raise UserDoesNotExistError(f"Cannot find user with ID {id_}.")
return user["name"]
def username_to_userid(self, name: str):
"""Convert a Slack user name to their user ID"""
user_name = name.lstrip("@")
if user_name == self.auth["user"]:
return self.bot_identifier.userid
log.warning("Resolving user name '%s' by iterating all users", user_name)
user_id = None
try:
cursor = None
while True:
users_list = self.slack_web.users_list(cursor=cursor, limit=1000)
for user in users_list["members"]:
if user["name"] == user_name:
user_id = user["id"]
raise StopIteration
cursor = users_list["response_metadata"].get("next_cursor", None)
if not cursor:
raise UserDoesNotExistError(f"Cannot find user {user_name}.")
except StopIteration:
pass
log.warning("User '%s' resolved to user id '%s'", user_name, user_id)
return user_id
def channelid_to_channelname(self, id_: str):
"""Convert a Slack channel ID to its channel name"""
log.warning(f"get channel name from {id_}")
room = SlackRoom(self.slack_web, channelid=id_, bot=self)
return room.channelname
def channelname_to_channelid(self, name: str):
"""Convert a Slack channel name to its channel ID"""
log.warning(f"get channel id from {name}")
room = SlackRoom(self.slack_web, name=name, bot=self)
return room.id
def channels(
self,
exclude_archived=True,
joined_only=False,
types="public_channel,private_channel",
):
"""
Get all channels and groups and return information about them.
:param exclude_archived:
Exclude archived channels/groups
:param joined_only:
Filter out channels the bot hasn't joined
:param types:
Channel / Group types to search
:returns:
Lists all channels in a Slack team.
References:
- https://slack.com/api/conversations.list
"""
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
]
return channels
@lru_cache(1024)
def get_im_channel(self, id_):
"""Open a direct message channel to a user"""
try:
response = self.slack_web.conversations_open(users=id_)
return response["channel"]["id"]
except SlackAPIResponseError as e:
if e.error == "cannot_dm_bot":
log.info("Tried to DM a bot.")
return None
else:
raise e
def _prepare_message(self, msg): # or card
"""
Translates the common part of messaging for Slack.
:param msg: the message you want to extract the Slack concept from.
:return: a tuple to user human readable, the channel id
"""
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)
)
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."
)
to_channel_id = self.get_im_channel(msg.to.userid)
return to_humanreadable, to_channel_id
def send_message(self, msg):
super().send_message(msg)
if msg.parent is not None:
# we are asked to reply to a specify thread.
try:
msg.extras["thread_ts"] = self._ts_for_message(msg.parent)
except KeyError:
# Gives to the user a more interesting explanation if we cannot find a ts from the parent.
log.exception(
"The provided parent message is not a Slack message "
"or does not contain a Slack timestamp."
)
to_humanreadable = "<unknown>"
try:
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)
)
else:
to_humanreadable = msg.to.username
if isinstance(
msg.to, RoomOccupant
): # private to a room occupant -> this is a divert to private !
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)
else:
to_channel_id = msg.to.channelid
msgtype = "direct" if msg.is_direct else "channel"
log.debug(
"Sending %s message to %s (%s).",
msgtype,
to_humanreadable,
to_channel_id,
)
body = self.md.convert(msg.body)
log.debug("Message size: %d.", len(body))
parts = self.prepare_message_body(body, self.message_size_limit)
timestamps = []
for part in parts:
data = {
"channel": to_channel_id,
"text": part,
"unfurl_media": "true",
"link_names": "1",
"as_user": "true",
}
# Keep the thread_ts to answer to the same thread.
if "thread_ts" in msg.extras:
data["thread_ts"] = msg.extras["thread_ts"]
if msg.extras.get("ephemeral"):
data["user"] = msg.to.userid
# undo divert / room to private
if isinstance(msg.to, RoomOccupant):
data["channel"] = msg.to.channelid
result = self.slack_web.chat_postEphemeral(**data)
else:
result = self.slack_web.chat_postMessage(**data)
timestamps.append(result["ts"])
msg.extras["ts"] = timestamps
except Exception:
log.exception(
f"An exception occurred while trying to send the following message "
f"to {to_humanreadable}: {msg.body}."
)
def _slack_upload(self, stream: Stream) -> None:
"""
Performs an upload defined in a stream
:param stream: Stream object
:return: None
"""
try:
stream.accept()
resp = self.slack_web.files_upload(
channels=stream.identifier.channelid, filename=stream.name, file=stream
)
if "ok" in resp and resp["ok"]:
stream.success()
else:
stream.error()
except Exception:
log.exception(
f"Upload of {stream.name} to {stream.identifier.channelname} failed."
)
def send_stream_request(
self,
user: Identifier,
fsource: BinaryIO,
name: str = None,
size: int = None,
stream_type: str = None,
) -> Stream:
"""
Starts a file transfer. For Slack, the size and stream_type are unsupported
:param user: is the identifier of the person you want to send it to.
:param fsource: is a file object you want to send.
:param name: is an optional filename for it.
:param size: not supported in Slack backend
:param stream_type: not supported in Slack backend
:return Stream: object on which you can monitor the progress of it.
"""
stream = Stream(user, fsource, name, size, stream_type)
log.debug(
"Requesting upload of %s to %s (size hint: %d, stream type: %s).",
name,
user.channelname,
size,
stream_type,
)
self.thread_pool.apply_async(self._slack_upload, (stream,))
return stream
def send_card(self, card: Card):
if isinstance(card.to, RoomOccupant):
card.to = card.to.room
to_humanreadable, to_channel_id = self._prepare_message(card)
attachment = {}
if card.summary:
attachment["pretext"] = card.summary
if card.title:
attachment["title"] = card.title
if card.link:
attachment["title_link"] = card.link
if card.image:
attachment["image_url"] = card.image
if card.thumbnail:
attachment["thumb_url"] = card.thumbnail
if 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
]
parts = self.prepare_message_body(card.body, self.message_size_limit)
part_count = len(parts)
footer = attachment.get("footer", "")
for i in range(part_count):
if part_count > 1:
attachment["footer"] = f"{footer} [{i + 1}/{part_count}]"
attachment["text"] = parts[i]
data = {
"channel": to_channel_id,
"attachments": json.dumps([attachment]),
"link_names": "1",
"as_user": "true",
}
try:
log.debug("Sending data:\n%s", data)
self.slack_web.chat_postMessage(**data)
except Exception:
log.exception(
f"An exception occurred while trying to send a card to {to_humanreadable}.[{card}]"
)
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"
)
@staticmethod
def prepare_message_body(body, size_limit):
"""
Returns the parts of a message chunked and ready for sending.
This is a staticmethod for easier testing.
Args:
body (str)
size_limit (int): chunk the body into sizes capped at this maximum
Returns:
[str]
"""
fixed_format = body.startswith("```") # hack to fix the formatting
parts = list(split_string_after(body, size_limit))
if len(parts) == 1:
# If we've got an open fixed block, close it out
if parts[0].count("```") % 2 != 0:
parts[0] += "\n```\n"
else:
for i, part in enumerate(parts):
starts_with_code = part.startswith("```")
# If we're continuing a fixed block from the last part
if fixed_format and not starts_with_code:
parts[i] = "```\n" + part
# If we've got an open fixed block, close it out
if part.count("```") % 2 != 0:
parts[i] += "\n```\n"
return parts
@staticmethod
def extract_identifiers_from_string(text):
"""
Parse a string for Slack user/channel IDs.
Supports strings with the following formats::
<#C12345>
<#C12345|channel>
<@U12345>
<@U12345|user>
@user
#channel/user
#channel
Returns the tuple (username, userid, channelname, channelid).
Some elements may come back as None.
"""
exception_message = (
"Unparseable slack identifier, should be of the format `<#C12345>`, `<@U12345>`, "
"`<@U12345|user>`, `@user`, `#channel/user` or `#channel`. (Got `%s`)"
)
text = text.strip()
if text == "":
raise ValueError(exception_message % "")
channelname = None
username = None
channelid = None
userid = None
if text[0] == "<" and text[-1] == ">":
exception_message = (
"Unparseable slack ID, should start with U, B, C, G, D or W (got `%s`)"
)
text = text[2:-1]
if text == "":
raise ValueError(exception_message % "")
if text[0] in ("U", "B", "W"):
if "|" in text:
userid, username = text.split("|")
else:
userid = text
elif text[0] in ("C", "G", "D"):
if "|" in text:
channelid, channelname = text.split("|")
else:
channelid = text
else:
raise ValueError(exception_message % text)
elif text[0] == "@":
username = text[1:]
elif text[0] == "#":
plainrep = text[1:]
if "/" in text:
channelname, username = plainrep.split("/", 1)
else:
channelname = plainrep
else:
raise ValueError(exception_message % text)
return username, userid, channelname, channelid
def build_identifier(self, txtrep):
"""
Build a :class:`SlackIdentifier` from the given string txtrep.
Supports strings with the formats accepted by
:func:`~extract_identifiers_from_string`.
"""
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:
channelid = self.channelname_to_channelid(channelname)
if userid is not None and channelid is not None:
return SlackRoomOccupant(self.slack_web, userid, channelid, bot=self)
if userid is not None:
if userid == self.bot_identifier.userid:
return self.bot_identifier
return SlackPerson(self.slack_web, userid, self.get_im_channel(userid))
if channelid is not None:
return SlackRoom(webclient=self.slack_web, channelid=channelid, bot=self)
raise Exception(
"You found a bug. I expected at least one of userid, channelid, username or channelname "
"to be resolved but none of them were. This shouldn't happen so, please file a bug."
)
def is_from_self(self, msg: Message) -> bool:
return self.bot_identifier.userid == msg.frm.userid
def build_reply(self, msg, text=None, private=False, threaded=False):
response = self.build_message(text)
if "thread_ts" in msg.extras["slack_event"]:
# If we reply to a threaded message, keep it in the thread.
response.extras["thread_ts"] = msg.extras["slack_event"]["thread_ts"]
elif threaded:
# otherwise check if we should start a new thread
response.parent = msg
response.frm = self.bot_identifier
if private:
response.to = msg.frm
else:
response.to = msg.frm.room if isinstance(msg.frm, RoomOccupant) else msg.frm
return response
def add_reaction(self, msg: Message, reaction: str) -> None:
"""
Add the specified reaction to the Message if you haven't already.
:param msg: A Message.
:param reaction: A str giving an emoji, without colons before and after.
:raises: ValueError if the emoji doesn't exist.
"""
return self._react("reactions.add", msg, reaction)
def remove_reaction(self, msg: Message, reaction: str) -> None:
"""