-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path__init__.py
329 lines (264 loc) · 13.5 KB
/
__init__.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
"""
This file contains the base Picard skill class and methods relating to reacting
to different types of events.
"""
import asyncio
import logging
from textwrap import dedent
from markdown import markdown
from parse import parse
from opsdroid.connector.matrix import ConnectorMatrix
from opsdroid.connector.slack import ConnectorSlack
from opsdroid.connector.slack import events as slack_events
from opsdroid.events import (JoinGroup, JoinRoom, Message, NewRoom,
OpsdroidStarted, RoomDescription, RoomName,
UserInvite)
from opsdroid.matchers import match_event, match_regex
from opsdroid.skill import Skill
from .picard.commands import PicardCommands
from .picard.constraints import (admin_command, constrain_matrix_connector,
constrain_slack_connector, ignore_appservice_users)
from .picard.matrix import MatrixMixin
from .picard.matrix_groups import MatrixCommunityMixin
from .picard.slackbridge import SlackBridgeMixin
from .picard.util import RoomMemory
_LOGGER = logging.getLogger(__name__)
class Picard(Skill, PicardCommands, MatrixMixin, SlackBridgeMixin, MatrixCommunityMixin):
def __init__(self, opsdroid, config, *args, **kwargs):
super().__init__(opsdroid, config, *args, **kwargs)
self._slack_channel_lock = asyncio.Lock()
self._slack_rename_lock = asyncio.Lock()
self.memory = RoomMemory(self.opsdroid)
@property
def matrix_connector(self):
return self.opsdroid._connector_names['matrix']
@property
def slack_connector(self):
return self.opsdroid._connector_names['slack']
@match_regex('!ping')
@admin_command
async def ping(self, message):
return await message.respond("Captain Picard is on the bridge.")
@match_regex(r'!memory (?P<key>[^\s]+)')
async def memory_command(self, message):
key = message.regex['key']
_LOGGER.debug(f"Attempting to get {key} from {message.target} room memory.")
with self.memory[message.target]:
data = await self.opsdroid.memory.get(key)
return await message.respond(str(data))
@match_regex('!bridgeall')
@match_event(OpsdroidStarted)
@admin_command
async def bridge_all_slack_channels(self, message):
"""
Iterate over all slack channels and bridge them one by one.
"""
if (isinstance(message, OpsdroidStarted) and
not self.config.get("copy_from_slack_startup", True)):
await self.opsdroid.send(Message("Picard has started up, not bridging all channels as disabled in config.", target="main"))
return
await self.opsdroid.send(Message("Running the bridgeall command.", target="main"))
channels = await self.get_slack_channel_mapping()
for slack_channel_id, channel in channels.items():
slack_channel_name = channel['name']
_LOGGER.info(f"Processing... {slack_channel_name}")
matrix_room_id = await self.join_or_create_matrix_room(slack_channel_name)
# TODO: This iteration doesn't include archived channels.
if channel['is_archived'] and matrix_room_id:
# await self.archive_matrix_room(matrix_room_id)
continue
if not matrix_room_id:
matrix_room_id = await self.create_new_matrix_room()
await self.configure_new_matrix_room_pre_bridge(matrix_room_id,
self.config.get("make_public", False))
# Link the two rooms
await self.link_room(matrix_room_id, slack_channel_id)
# Setup the matrix room
await self.configure_new_matrix_room_post_bridge(matrix_room_id,
slack_channel_name,
channel['topic']['value'],
_bridgeall=False)
await self.opsdroid.send(Message("Finished adding all channels.",
target="main",
connector=self.matrix_connector))
@match_event(slack_events.ChannelArchived)
async def on_archive_slack_channel(self, archive):
_LOGGER.info(f"Got slack archive event for {archive.target}")
matrix_room_id = await self.matrix_room_id_from_slack_channel_id(archive.target)
if not matrix_room_id:
_LOGGER.debug(f"Could not get matrix room id for slack channel {archive.target} to archive it.")
return
await self.archive_matrix_room(matrix_room_id)
await self.unlink_room(matrix_room_id, archive.target)
@match_event(slack_events.ChannelUnarchived)
async def on_unarchive_slack_channel(self, unarchive):
matrix_room_id = await self.matrix_room_id_from_slack_channel_id(unarchive.target)
if matrix_room_id:
_LOGGER.debug(f"Found exisiting matrix room for slack channel {unarchive.target} unarchiving it.")
await self.unarchive_matrix_room(matrix_room_id)
name = await self.get_slack_channel_name(unarchive.target)
new_room = NewRoom(name=name,
target=unarchive.target,
connector=unarchive.connector)
return await self.on_new_slack_channel(new_room)
@match_event(NewRoom)
@constrain_slack_connector
async def on_new_slack_channel(self, channel):
"""
React to a new slack channel event.
"""
# If we have created a slack channel we want to not react to it.
if self._slack_channel_lock.locked():
_LOGGER.info("Ignoring channel create event from slack, creation locked.")
return
is_public = self.config.get("make_public", False)
matrix_room_id = await self.join_or_create_matrix_room(channel.name)
await self.configure_new_matrix_room_pre_bridge(matrix_room_id,
is_public)
# Link the two rooms
await self.link_room(matrix_room_id, channel.target)
# Retrieve topic from slack
topic = await self.get_slack_channel_topic(channel.target)
# Setup the matrix room
canonical_alias = await self.configure_new_matrix_room_post_bridge(matrix_room_id,
channel.name,
topic)
await self.announce_new_room(canonical_alias, channel.user, topic)
@match_event(RoomDescription)
async def on_topic_change(self, topic):
"""Handle a topic change."""
_LOGGER.debug(f"Got RoomDescription object from {topic.connector.name}")
if topic.connector is self.matrix_connector:
with self.memory[topic.target]:
room_options = await self.opsdroid.memory.get("picard.options") or {}
if not room_options.get("skip_room_description"):
_LOGGER.debug(f"Setting slack room description to: {topic.description}")
slack_channel_id = await self.slack_channel_id_from_matrix_room_id(topic.target)
await self.set_slack_channel_description(slack_channel_id, topic.description)
else:
_LOGGER.debug("Matrix Connector: Not setting topic because of room options.")
elif topic.connector is self.slack_connector:
user_id = await self._id_for_slack_user_token()
if topic.raw_event['user'] == user_id:
return
slack_channel_name = await self.get_slack_channel_name(topic.target)
matrix_room_id = await self.matrix_room_id_from_slack_channel_name(slack_channel_name)
with self.memory[matrix_room_id]:
room_options = await self.opsdroid.memory.get("picard.options") or {}
if not room_options.get("skip_room_description"):
_LOGGER.debug(f"Setting matrix room description to: {topic.description}")
topic.target = matrix_room_id
topic.connector = self.matrix_connector
topic.description = self.clean_slack_message(topic.description)
await self.opsdroid.send(topic)
else:
_LOGGER.debug(f"{room_options}")
_LOGGER.debug("Slack Connector: Not setting topic because of room options.")
# This is misbehaving, disabling for pyastro20
# @match_event(RoomName)
async def on_name_change(self, room_name):
"""Handle a room name change."""
name_template = self.config.get("room_name_template")
if not name_template:
return
if room_name.connector is self.matrix_connector:
name = parse(name_template, room_name.name)
name = name or room_name.name
matrix_room_id = room_name.target
slack_channel_id = await self.slack_channel_id_from_matrix_room_id(room_name.target)
old_name = await self.get_slack_channel_name(slack_channel_id)
if room_name.connector is self.slack_connector:
if self._slack_rename_lock.locked():
return
slack_channel_id = room_name.target
old_name = room_name.raw_event['old_name']
matrix_room_id = await self.matrix_room_id_from_slack_channel_name(old_name)
name = room_name.name
if old_name == name:
return
with self.memory[matrix_room_id]:
room_options = await self.opsdroid.memory.get("picard.options") or {}
if room_options.get("skip_room_name"):
return
# Remove the aliases for the old name
await self.remove_room_aliases(old_name)
# Add new aliases
await self.configure_room_aliases(matrix_room_id, name)
if room_name.connector is self.matrix_connector:
async with self._slack_rename_lock:
await self.set_slack_channel_name(slack_channel_id, name)
if room_name.connector is self.slack_connector:
new_name = RoomName(name=name_template.format(name=name),
target=matrix_room_id,
connector=self.matrix_connector)
return await self.opsdroid.send(new_name)
@match_event(UserInvite)
@constrain_matrix_connector
async def on_invite_to_room(self, invite):
"""
Join all rooms on invite.
"""
await invite.respond(JoinRoom())
if await self.is_one_to_one_chat(invite.target):
dms = await self.opsdroid.memory.get("direct_messages") or {}
dms.update({invite.raw_event['sender']: invite.target})
await self.opsdroid.memory.put("direct_messages", dms)
return await self.send_matrix_welcome_message(invite.target)
@match_event(JoinGroup)
@constrain_matrix_connector
async def on_new_community_user(self, join):
"""
React to a new user joining the community on matrix.
"""
dms = await self.opsdroid.memory.get("direct_messages") or {}
if join.user_id not in dms:
matrix_room_id = await self.create_new_matrix_direct_message(join.user_id)
dms.update({join.user_id: matrix_room_id})
await self.opsdroid.memory.put("direct_messages", dms)
else:
matrix_room_id = dms[join.user_id]
await self.send_matrix_welcome_message(matrix_room_id)
async def send_matrix_welcome_message(self, matrix_room_id):
"""
Send the welcome message to a matrix 1-1.
"""
welcome_message = self.config.get('welcome', {}).get('matrix')
if welcome_message:
welcome_message = markdown(dedent(welcome_message))
return await self.opsdroid.send(Message(welcome_message,
target=matrix_room_id,
connector=self.matrix_connector))
@match_event(JoinGroup)
@constrain_slack_connector
async def on_new_team_user(self, join):
"""
React to a new user joining the team on slack.
"""
return await self.send_slack_welcome_message(join.user_id)
async def send_slack_welcome_message(self, slack_user_id):
"""
Send the welcome message to a slack 1-1.
"""
welcome_message = self.config.get('welcome', {}).get('slack')
slack_room_id = await self.get_slack_direct_message_channel(slack_user_id)
if welcome_message:
return await self.opsdroid.send(Message(dedent(welcome_message),
target=slack_room_id,
connector=self.slack_connector))
async def announce_new_room(self, matrix_room_alias, username, topic):
"""
Send a message to the configured room announcement room.
"""
room_name = self.config.get("announcement_room_name")
if not room_name:
return
matrix_room_id = await self.matrix_room_id_from_slack_channel_name(room_name)
pill = f'<a href="https://matrix.to/#/{matrix_room_alias}">{matrix_room_alias}</a>'
text = f"{username} just created the {pill} room"
if topic:
text += f" for discussing '{topic}'"
text += '.'
await self.opsdroid.send(Message(
text=text,
target=matrix_room_id,
connector=self.matrix_connector))