Repository navigation
Expand file tree
/
Copy pathplugin.py
More file actions
292 lines (242 loc) · 10.2 KB
/
Copy pathplugin.py
File metadata and controls
292 lines (242 loc) · 10.2 KB
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
"""
.. module: dispatch.plugins.dispatch_slack.plugin
:platform: Unix
:copyright: (c) 2019 by Netflix Inc., see AUTHORS for more
:license: Apache, see LICENSE for more details.
.. moduleauthor:: Kevin Glisson <kglisson@netflix.com>
"""
from joblib import Memory
from typing import List, Optional
import logging
import os
import re
from dispatch.conversation.enums import ConversationCommands
from dispatch.decorators import apply, counter, timer
from dispatch.exceptions import DispatchPluginException
from dispatch.plugins import dispatch_slack as slack_plugin
from dispatch.plugins.bases import ConversationPlugin, DocumentPlugin, ContactPlugin
from .config import (
SLACK_COMMAND_ASSIGN_ROLE_SLUG,
SLACK_COMMAND_ENGAGE_ONCALL_SLUG,
SLACK_COMMAND_REPORT_EXECUTIVE_SLUG,
SLACK_COMMAND_LIST_PARTICIPANTS_SLUG,
SLACK_COMMAND_LIST_RESOURCES_SLUG,
SLACK_COMMAND_LIST_TASKS_SLUG,
SLACK_COMMAND_REPORT_TACTICAL_SLUG,
SLACK_COMMAND_UPDATE_INCIDENT_SLUG,
SLACK_PROFILE_DEPARTMENT_FIELD_ID,
SLACK_PROFILE_TEAM_FIELD_ID,
SLACK_PROFILE_WEBLINK_FIELD_ID,
)
from .views import router as slack_event_router
from .messaging import create_message_blocks
from .service import (
create_slack_client,
add_users_to_conversation,
archive_conversation,
unarchive_conversation,
create_conversation,
get_conversation_by_name,
get_user_avatar_url,
get_user_email,
get_user_info_by_id,
get_user_profile_by_email,
get_user_username,
list_conversation_messages,
list_conversations,
message_filter,
open_dialog_with_user,
open_modal_with_user,
resolve_user,
send_ephemeral_message,
send_message,
set_conversation_topic,
chunks,
)
logger = logging.getLogger(__name__)
command_mappings = {
ConversationCommands.assign_role: SLACK_COMMAND_ASSIGN_ROLE_SLUG,
ConversationCommands.update_incident: SLACK_COMMAND_UPDATE_INCIDENT_SLUG,
ConversationCommands.engage_oncall: SLACK_COMMAND_ENGAGE_ONCALL_SLUG,
ConversationCommands.executive_report: SLACK_COMMAND_REPORT_EXECUTIVE_SLUG,
ConversationCommands.list_participants: SLACK_COMMAND_LIST_PARTICIPANTS_SLUG,
ConversationCommands.list_resources: SLACK_COMMAND_LIST_RESOURCES_SLUG,
ConversationCommands.list_tasks: SLACK_COMMAND_LIST_TASKS_SLUG,
ConversationCommands.tactical_report: SLACK_COMMAND_REPORT_TACTICAL_SLUG,
}
@apply(counter, exclude=["__init__"])
@apply(timer, exclude=["__init__"])
class SlackConversationPlugin(ConversationPlugin):
title = "Slack Plugin - Conversation Management"
slug = "slack-conversation"
description = "Uses Slack to facilitate conversations."
version = slack_plugin.__version__
events = slack_event_router
author = "Netflix"
author_url = "https://github.com/netflix/dispatch.git"
def __init__(self):
self.client = create_slack_client()
def create(self, name: str, is_private: bool = True):
"""Creates a new Slack conversation."""
return create_conversation(self.client, name, is_private)
def send(
self,
conversation_id: str,
text: str,
message_template: List[dict],
notification_type: str,
items: Optional[List] = None,
blocks: Optional[List] = None,
persist: bool = False,
**kwargs,
):
"""Sends a new message based on data and type."""
if not blocks:
blocks = create_message_blocks(message_template, notification_type, items, **kwargs)
for c in chunks(blocks, 50):
send_message(self.client, conversation_id, text, c, persist)
def send_direct(
self,
user: str,
text: str,
message_template: dict,
notification_type: str,
items: Optional[List] = None,
blocks: Optional[List] = None,
**kwargs,
):
"""Sends a message directly to a user."""
user_id = resolve_user(self.client, user)["id"]
if not blocks:
blocks = create_message_blocks(message_template, notification_type, items, **kwargs)
return send_message(self.client, user_id, text, blocks)
def send_ephemeral(
self,
conversation_id: str,
user: str,
text: str,
message_template: dict = None,
notification_type: str = None,
items: Optional[List] = None,
blocks: Optional[List] = None,
**kwargs,
):
"""Sends an ephemeral message to a user in a channel."""
user_id = resolve_user(self.client, user)["id"]
if not blocks:
blocks = create_message_blocks(message_template, notification_type, items, **kwargs)
return send_ephemeral_message(self.client, conversation_id, user_id, text, blocks)
def add(self, conversation_id: str, participants: List[str]):
"""Adds users to conversation."""
participants = [resolve_user(self.client, p)["id"] for p in participants]
return add_users_to_conversation(self.client, conversation_id, participants)
def open_dialog(self, trigger_id: str, dialog: dict):
"""Opens a dialog with a user."""
return open_dialog_with_user(self.client, trigger_id, dialog)
def archive(self, conversation_id: str):
"""Archives conversation."""
return archive_conversation(self.client, conversation_id)
def unarchive(self, conversation_id: str):
"""Unarchives conversation."""
return unarchive_conversation(self.client, conversation_id)
def get_participant_username(self, participant_id: str):
"""Gets the participant's username."""
return get_user_username(self.client, participant_id)
def get_participant_email(self, participant_id: str):
"""Gets the participant's email."""
return get_user_email(self.client, participant_id)
def get_participant_avatar_url(self, participant_id: str):
"""Gets the participant's avatar url."""
return get_user_avatar_url(self.client, participant_id)
def set_topic(self, conversation_id: str, topic: str):
"""Sets the conversation topic."""
return set_conversation_topic(self.client, conversation_id, topic)
def get_command_name(self, command: str):
"""Gets the command name."""
return command_mappings.get(command, [])
def open_modal(self, trigger_id: str, modal: dict):
"""Opens a modal with a user."""
return open_modal_with_user(client=self.client, trigger_id=trigger_id, modal=modal)
@apply(counter, exclude=["__init__"])
@apply(timer, exclude=["__init__"])
class SlackContactPlugin(ContactPlugin):
title = "Slack Plugin - Contact Information Resolver"
slug = "slack-contact"
description = "Uses Slack to resolve contact information details."
version = slack_plugin.__version__
author = "Netflix"
author_url = "https://github.com/netflix/dispatch.git"
def __init__(self):
self.client = create_slack_client()
def get(self, email: str, **kwargs):
"""Fetch user info by email."""
team = department = weblink = "Unknown"
profile = get_user_profile_by_email(self.client, email)
profile_fields = profile.get("fields")
if profile_fields:
team = profile_fields.get(SLACK_PROFILE_TEAM_FIELD_ID, {}).get("value", "Unknown")
department = profile_fields.get(SLACK_PROFILE_DEPARTMENT_FIELD_ID, {}).get(
"value", "Unknown"
)
weblink = profile_fields.get(SLACK_PROFILE_WEBLINK_FIELD_ID, {}).get("value", "Unknown")
return {
"fullname": profile["real_name"],
"email": profile["email"],
"title": profile["title"],
"team": team,
"department": department,
"location": profile["tz"],
"weblink": weblink,
"thumbnail": profile["image_512"],
}
class SlackDocumentPlugin(DocumentPlugin):
title = "Slack Plugin - Document Interrogator"
slug = "slack-document"
description = "Uses Slack as a document source."
version = slack_plugin.__version__
author = "Netflix"
author_url = "https://github.com/netflix/dispatch.git"
def __init__(self):
self.cachedir = os.path.dirname(os.path.realpath(__file__))
self.memory = Memory(cachedir=self.cachedir, verbose=0)
self.client = create_slack_client()
def get(self, **kwargs) -> dict:
"""Queries slack for documents."""
conversations = []
if kwargs["channels"]:
logger.debug(f"Querying slack for documents. Channels: {kwargs['channels']}")
channels = kwargs["channels"].split(",")
for c in channels:
conversations.append(get_conversation_by_name(self.client, c))
if kwargs["channel_match_pattern"]:
try:
regex = kwargs["channel_match_pattern"]
pattern = re.compile(regex)
except re.error as e:
raise DispatchPluginException(
message=f"Invalid regex. Is everything escaped properly? Regex: '{regex}' Message: {e}"
)
logger.debug(
f"Querying slack for documents. ChannelsPattern: {kwargs['channel_match_pattern']}"
)
for c in list_conversations(self.client):
if pattern.match(c["name"]):
conversations.append(c)
for c in conversations:
logger.info(f'Fetching channel messages. Channel Name: {c["name"]}')
messages = list_conversation_messages(self.client, c["id"], lookback=kwargs["lookback"])
logger.info(f'Found {len(messages)} messages in slack. Channel Name: {c["name"]}')
for m in messages:
if not message_filter(m):
continue
user_email = get_user_info_by_id(self.client, m["user"])["user"]["profile"]["email"]
yield {
"person": {"email": user_email},
"doc": {
"text": m["text"],
"is_private": c["is_private"],
"subject": c["name"],
"source": "slack",
},
"ref": {"timestamp": m["ts"]},
}