-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathchannel_manager.py
More file actions
381 lines (316 loc) · 15.9 KB
/
Copy pathchannel_manager.py
File metadata and controls
381 lines (316 loc) · 15.9 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
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
import logging
import time
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
from config import Config
from state import StateBackend, BotState
logger = logging.getLogger(__name__)
class ChannelManager:
def __init__(self, client: WebClient, state_backend: StateBackend):
self.client = client
self.state = state_backend
def add_user_to_default_channels(self, user_id: str) -> None:
added = []
for channel_id in Config.DEFAULT_CHANNELS:
result = self._invite_user(channel_id, user_id)
if result and result != "guest":
added.append(channel_id)
if added:
logger.info(f"Added {user_id} to {len(added)} default channels")
def send_optin_prompts(self, user_id: str) -> None:
for channel_id, message in Config.OPTIN_CHANNELS.items():
try:
self.client.chat_postEphemeral(
channel=Config.OPTIN_PROMPT_CHANNEL,
user=user_id,
text=message,
blocks=[
{
"type": "section",
"text": {"type": "mrkdwn", "text": f"*{message}*\n\nJoin <#{channel_id}>?"}
},
{
"type": "actions",
"elements": [
{
"type": "button",
"text": {"type": "plain_text", "text": "Yes, join!"},
"style": "primary",
"action_id": "optin_join",
"value": channel_id,
},
{
"type": "button",
"text": {"type": "plain_text", "text": "No thanks"},
"action_id": "optin_decline",
"value": channel_id,
},
],
},
],
)
except SlackApiError as e:
logger.error(f"Failed to send opt-in prompt: {e.response['error']}")
def process_promoted_guest(self, user_id: str) -> bool:
if not self.state.is_pending_guest(user_id):
return False
self.state.remove_pending_guest(user_id)
return self.add_user_to_welcome_channel(user_id)
def add_user_to_welcome_channel(self, user_id: str) -> bool:
if self.state.is_user_processed(user_id):
return True
# Mark early to prevent race conditions
self.state.mark_user_processed(user_id)
self.add_user_to_default_channels(user_id)
self.send_optin_prompts(user_id)
current_state = self.state.get_state()
if not current_state.current_channel_id:
current_state = self._create_or_get_channel(current_state)
if not current_state.current_channel_id:
logger.error("Failed to create or find welcome channel")
return False
if current_state.current_count >= Config.BATCH_SIZE:
logger.info(f"Rotating to new channel (batch full: {current_state.current_count}/{Config.BATCH_SIZE})")
current_state = self._rotate_to_next_channel(current_state)
if not current_state.current_channel_id:
logger.error("Failed to create rotated welcome channel")
return False
result = self._invite_user(current_state.current_channel_id, user_id)
if result == "guest":
logger.info("Guest user will be added to welcome channel after promotion")
return True
if result:
current_state.current_count += 1
self.state.save_state(current_state)
# Only track add-time when auto-removal is enabled, so we don't
# store anyone when the feature is off.
if Config.REMOVAL_AFTER_DAYS > 0:
self.state.record_user_added(user_id, current_state.current_channel_id, time.time())
self._send_user_welcome(current_state.current_channel_id, user_id)
logger.info(f"Welcomed {user_id} to channel {current_state.current_channel_number} ({current_state.current_count}/{Config.BATCH_SIZE})")
else:
logger.error(f"Failed to invite {user_id} to welcome channel")
return bool(result)
def remove_expired_users(self) -> int:
"""Remove users who were added to a welcome channel longer than
Config.REMOVAL_AFTER_DAYS ago. Returns the number removed."""
if Config.REMOVAL_AFTER_DAYS <= 0:
return 0
cutoff = time.time() - Config.REMOVAL_AFTER_DAYS * 86400
expired = self.state.get_expired_users(cutoff)
if not expired:
return 0
protected, resolved = self._protected_user_ids()
if not resolved:
# Couldn't fully resolve which users are protected — skip this sweep
# rather than risk removing a configured member/group.
logger.warning("Skipping removal sweep: could not resolve protected group membership")
return 0
removed = 0
for user_id, channel_id in expired:
# Never remove configured welcome-channel members or group members.
if user_id in protected:
self.state.remove_tracked_user(user_id)
continue
if self._kick_user(channel_id, user_id):
self.state.remove_tracked_user(user_id)
removed += 1
if removed:
logger.info(f"Removed {removed} expired user(s) from welcome channel(s)")
return removed
def _protected_user_ids(self) -> tuple[set[str], bool]:
"""User IDs that must never be removed: configured members plus everyone
in the configured groups. Returns (ids, fully_resolved)."""
protected = set(Config.WELCOME_CHANNEL_MEMBERS)
resolved = True
for group_id in Config.WELCOME_CHANNEL_GROUPS:
try:
response = self.client.usergroups_users_list(usergroup=group_id)
protected.update(response.get("users", []))
except SlackApiError as e:
resolved = False
logger.warning(f"Failed to resolve protected group {group_id}: {e.response['error']}")
return protected, resolved
def _kick_user(self, channel_id: str, user_id: str) -> bool:
if not channel_id:
# No channel recorded — nothing to kick from, drop from tracking.
return True
max_retries = 3
for attempt in range(max_retries):
try:
self.client.conversations_kick(channel=channel_id, user=user_id)
logger.info(f"Removed expired user {user_id} from {channel_id}")
return True
except SlackApiError as e:
error = e.response["error"]
# Already gone / nothing to do — treat as success.
if error in ("not_in_channel", "user_not_in_channel", "user_not_found", "channel_not_found"):
return True
if error == "ratelimited":
retry_after = int(e.response.headers.get("Retry-After", 2 ** attempt))
logger.warning(f"Rate limited removing user, waiting {retry_after}s")
time.sleep(retry_after)
continue
# Permission/structural errors won't fix themselves on retry; stop
# tracking the user so we don't loop on them forever.
if error in ("cant_kick_self", "cant_kick_from_general", "restricted_action"):
logger.warning(f"Cannot remove user {user_id} from {channel_id}: {error}")
return True
logger.error(f"Failed to remove user {user_id} from {channel_id}: {error}")
return False
logger.error(f"Failed to remove user {user_id} from {channel_id} after max retries")
return False
def _create_or_get_channel(self, state: BotState) -> BotState:
channel_name = Config.get_channel_name(state.current_channel_number)
try:
response = self.client.conversations_create(name=channel_name, is_private=True)
channel_id = response["channel"]["id"]
state.current_channel_id = channel_id
state.current_count = 0
self.state.save_state(state)
self._post_welcome_message(channel_id)
self._add_default_members(channel_id)
logger.info(f"Created new channel: {channel_name}")
except SlackApiError as e:
error = e.response["error"]
if error == "name_taken":
state = self._find_existing_channel(state, channel_name)
if not state.current_channel_id:
logger.error(f"Channel {channel_name} exists but couldn't be found")
else:
logger.error(f"Failed to create channel: {error}")
return state
def _find_existing_channel(self, state: BotState, channel_name: str) -> BotState:
try:
cursor = None
while True:
for attempt in range(3):
try:
response = self.client.conversations_list(
types="private_channel",
exclude_archived=False,
limit=200,
cursor=cursor,
)
break
except SlackApiError as e:
if e.response["error"] == "ratelimited":
retry_after = int(e.response.headers.get("Retry-After", 5))
logger.warning(f"Rate limited, waiting {retry_after}s")
time.sleep(retry_after)
else:
raise
else:
logger.error("Failed to list channels after retries")
return state
for channel in response["channels"]:
if channel["name"] == channel_name:
channel_id = channel["id"]
if channel.get("is_archived"):
logger.info(f"Channel {channel_name} is archived, unarchiving...")
try:
self.client.conversations_unarchive(channel=channel_id)
except SlackApiError as e:
logger.error(f"Failed to unarchive: {e.response['error']}")
return state
self._ensure_bot_in_channel(channel_id)
state.current_channel_id = channel_id
info = self.client.conversations_info(channel=channel_id, include_num_members=True)
state.current_count = max(0, info["channel"].get("num_members", 1) - 1)
self.state.save_state(state)
logger.info(f"Found existing channel {channel_name} with {state.current_count} members")
return state
cursor = response.get("response_metadata", {}).get("next_cursor")
if not cursor:
break
except SlackApiError as e:
logger.error(f"Failed to find channel: {e.response['error']}")
return state
def _rotate_to_next_channel(self, state: BotState) -> BotState:
state.current_channel_number += 1
state.current_channel_id = None
state.current_count = 0
return self._create_or_get_channel(state)
def _ensure_bot_in_channel(self, channel_id: str) -> bool:
try:
self.client.conversations_join(channel=channel_id)
return True
except SlackApiError as e:
error = e.response["error"]
# Private channels can't be joined - bot must already be member or create it
if error in ("already_in_channel", "method_not_supported_for_channel_type"):
return True
logger.error(f"Bot failed to join channel {channel_id}: {error}")
return False
def _invite_user(self, channel_id: str, user_id: str) -> bool | str:
max_retries = 3
if not self._ensure_bot_in_channel(channel_id):
return False
for attempt in range(max_retries):
try:
self.client.conversations_invite(channel=channel_id, users=user_id)
return True
except SlackApiError as e:
error = e.response["error"]
if error == "already_in_channel":
return True
if error == "ratelimited":
retry_after = int(e.response.headers.get("Retry-After", 2 ** attempt))
logger.warning(f"Rate limited, waiting {retry_after}s")
time.sleep(retry_after)
continue
if error in ("user_is_restricted", "user_is_ultra_restricted"):
logger.info(f"Skipping guest user for channel {channel_id}")
return "guest"
if error in ("cant_invite_self", "user_not_found", "method_not_supported_for_channel_type"):
logger.info(f"Skipping user ({error})")
return True
logger.error(f"Failed to invite user: {error}")
return False
logger.error("Failed to invite user after max retries")
return False
def _send_user_welcome(self, channel_id: str, user_id: str) -> None:
try:
self.client.chat_postEphemeral(
channel=channel_id,
user=user_id, # REQUIRED
text=Config.WELCOME_MESSAGE,
)
except SlackApiError as e:
logger.error(f"Failed to send welcome message: {e.response['error']}")
def _add_default_members(self, channel_id: str) -> None:
added_count = 0
for user_id in Config.WELCOME_CHANNEL_MEMBERS:
try:
self.client.conversations_invite(channel=channel_id, users=user_id)
added_count += 1
except SlackApiError as e:
if e.response["error"] != "already_in_channel":
logger.warning(f"Failed to add member {user_id}: {e.response['error']}")
for group_id in Config.WELCOME_CHANNEL_GROUPS:
try:
response = self.client.usergroups_users_list(usergroup=group_id)
users = response.get("users", [])
for user_id in users:
try:
self.client.conversations_invite(channel=channel_id, users=user_id)
added_count += 1
except SlackApiError as e:
if e.response["error"] != "already_in_channel":
logger.warning(f"Failed to add group member {user_id}: {e.response['error']}")
except SlackApiError as e:
logger.warning(f"Failed to get group {group_id} members: {e.response['error']}")
def _post_welcome_message(self, channel_id: str) -> None:
try:
response = self.client.chat_postEphemeral(
channel=channel_id,
text=Config.WELCOME_MESSAGE,
unfurl_links=False,
)
if Config.PIN_WELCOME_MESSAGE and response.get("ts"):
try:
self.client.pins_add(channel=channel_id, timestamp=response["ts"])
except SlackApiError as e:
logger.warning(f"Failed to pin message: {e.response['error']}")
except SlackApiError as e:
logger.error(f"Failed to post welcome message: {e.response['error']}")