Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 38 additions & 24 deletions automator/src/lambda_function.py
Original file line number Diff line number Diff line change
Expand Up @@ -573,12 +573,20 @@ def handle_repost_to_thread_and_delete(event, reaction_config):
logger.info(f"Deleted original message from channel {channel} (kept in thread)")


def _delete_message(channel, ts):
def _delete_message(channel, ts, thread_ts=None):
if FAKE_DELETE:
logger.info(f"FAKE_DELETE for {channel} {ts}")
return True

response = slack.remove_message(channel, ts)
try:
if thread_ts and thread_ts != ts:
response = slack.remove_message(channel, ts, thread_ts=thread_ts)
else:
response = slack.remove_message(channel, ts)
except Exception as exc:
logger.warning(f"delete raised for {channel} {ts}: {exc}")
return False

if isinstance(response, dict) and not response.get('ok', False):
logger.info(
f"delete failed for {channel} {ts}: {response.get('error')}"
Expand Down Expand Up @@ -682,13 +690,11 @@ def handle_ban_user(event, reaction_config):
moderator = event.get('user')

message_details = slack.get_message_content(channel, ts)
if not message_details:
logger.info(f"Ban: reacted message not found for {channel} {ts}")
return

target_user_id = message_details.get('user')
target_user_id = (
message_details.get('user') if message_details else event.get('item_user')
)
if not target_user_id:
logger.info("Ban: reacted message has no user; aborting")
logger.info(f"Ban: reacted message user not found for {channel} {ts}; aborting")
return

if target_user_id in set(config.get('admins', [])):
Expand All @@ -706,26 +712,34 @@ def handle_ban_user(event, reaction_config):
cutoff_ts = time.time() - lookback_hours * 3600

search_matches = []
if username:
search_matches = slack.search_user_messages(username, after_date)
search_matches = [
m for m in search_matches
if float(m.get('ts', 0)) >= cutoff_ts
]
logger.info(
f"Ban: found {len(search_matches)} messages for @{username} "
f"since {after_date}"
)
if username or target_user_id:
try:
search_matches = slack.search_user_messages(
username, after_date, user_id=target_user_id
)
search_matches = [
m for m in search_matches
if float(m.get('ts', 0)) >= cutoff_ts
]
logger.info(
f"Ban: found {len(search_matches)} messages for {target_user_id} "
f"(@{username}) since {after_date}"
)
except Exception as exc:
logger.warning(f"Ban: search_user_messages failed for {target_user_id}: {exc}")
else:
logger.info(f"Ban: could not resolve username for {target_user_id}; deleting reacted message only")
logger.info(f"Ban: could not resolve user for {target_user_id}; deleting reacted message only")

matches = [_seed_ban_message(channel, ts, message_details)]
seen = {_message_key(matches[0])}
seed_msg = _seed_ban_message(channel, ts, message_details or {})
matches = [seed_msg]
seen = {_message_key(seed_msg): seed_msg}
for match in search_matches:
key = _message_key(match)
if key not in seen:
matches.append(match)
seen.add(key)
seen[key] = match
elif not seen[key].get('thread_ts') and match.get('thread_ts'):
seen[key]['thread_ts'] = match['thread_ts']

reply_template = reaction_config.get('reply_message')
deleted = set()
Expand Down Expand Up @@ -756,14 +770,14 @@ def handle_ban_user(event, reaction_config):
)
slack.send_dm(reply_user, notification)

if _delete_message(msg_channel, reply_ts):
if _delete_message(msg_channel, reply_ts, thread_ts=msg_ts):
deleted.add(key)
replies_deleted += 1

key = (msg_channel, msg_ts)
if key in deleted:
continue
if _delete_message(msg_channel, msg_ts):
if _delete_message(msg_channel, msg_ts, thread_ts=thread_ts):
deleted.add(key)
parent_deleted += 1

Expand Down
133 changes: 84 additions & 49 deletions automator/src/slack.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,56 +91,78 @@ def find_message_by_ts(messages, ts):
return None


def get_message_content(channel, ts):
params = {
'channel': channel,
'ts': ts
}

headers = {
'Authorization': f'Bearer {SLACK_TOKEN}'
}

url = 'https://slack.com/api/conversations.replies'
response = requests.get(url, params=params, headers=headers)
response.raise_for_status()

response_json = response.json()
all_messages = response_json.get('messages', [])
if not all_messages:
return None
message = find_message_by_ts(all_messages, ts)
return message
_CONVERSATIONS_FALLBACK_ERRORS = {
'not_in_channel',
'channel_not_found',
'missing_scope',
'not_allowed_token_type',
}


def _candidate_tokens():
tokens = [SLACK_TOKEN]
if USER_SLACK_TOKEN and USER_SLACK_TOKEN != SLACK_TOKEN:
tokens.append(USER_SLACK_TOKEN)
return tokens


def _conversations_get(method, params):
url = f'https://slack.com/api/{method}'
tokens = _candidate_tokens()
last_json = {}
for idx, token in enumerate(tokens):
headers = {'Authorization': f'Bearer {token}'}
response = requests.get(url, params=params, headers=headers)
response.raise_for_status()
response_json = response.json()
last_json = response_json
if response_json.get('ok', True):
return response_json
error = response_json.get('error')
if error not in _CONVERSATIONS_FALLBACK_ERRORS or idx == len(tokens) - 1:
logger.info(f"{method} failed for {params}: {error}")
return response_json
return last_json


def get_message_content(channel, ts, thread_ts=None):
if thread_ts and thread_ts != ts:
thread_json = _conversations_get(
'conversations.replies', {'channel': channel, 'ts': thread_ts}
)
message = find_message_by_ts(thread_json.get('messages', []), ts)
if message:
return message

response_json = _conversations_get(
'conversations.replies', {'channel': channel, 'ts': ts}
)
message = find_message_by_ts(response_json.get('messages', []), ts)
if message:
return message

# Fallback for top-level messages when conversations.replies fails or misses.
history_json = _conversations_get(
'conversations.history',
{'channel': channel, 'latest': ts, 'inclusive': True, 'limit': 1},
)
return find_message_by_ts(history_json.get('messages', []), ts)


def get_thread_replies(channel, ts, include_parent=False):
"""Get all replies in a thread (optionally including the parent message)"""
params = {
'channel': channel,
'ts': ts
}

headers = {
'Authorization': f'Bearer {SLACK_TOKEN}'
}

url = 'https://slack.com/api/conversations.replies'
response = requests.get(url, params=params, headers=headers)
response.raise_for_status()

response_json = response.json()
response_json = _conversations_get(
'conversations.replies', {'channel': channel, 'ts': ts}
)
if not response_json.get('ok', True):
logger.info(f"conversations.replies failed for {channel} {ts}: {response_json.get('error')}")
return []

all_messages = response_json.get('messages', [])
if include_parent:
return all_messages

# Filter out the parent message (first message with ts == thread_ts)
thread_replies = [msg for msg in all_messages if msg['ts'] != ts]

return thread_replies
return [msg for msg in all_messages if msg['ts'] != ts]


def get_thread_messages(channel, ts):
Expand Down Expand Up @@ -188,11 +210,14 @@ def send_dm_blocks(user, message, blocks):
return response.json()


def remove_message(channel, ts):
def remove_message(channel, ts, thread_ts=None):
# Keep the guard at the sole chat.delete boundary so every deletion path,
# including ban sweeps and thread replies, must first preserve the message.
try:
message = get_message_content(channel, ts)
if thread_ts and thread_ts != ts:
message = get_message_content(channel, ts, thread_ts=thread_ts)
else:
message = get_message_content(channel, ts)
except Exception:
alert_deletion_audit('AUDIT_DELETED_MESSAGE_FAILED', channel, ts)
raise RuntimeError('Deletion skipped: full message fetch failed') from None
Expand Down Expand Up @@ -259,15 +284,8 @@ def get_user_info(user_id):
return response_json.get('user')


def search_user_messages(username, after_date):
"""Find messages from a given Slack username posted on or after `after_date` (YYYY-MM-DD).

Uses search.messages, which requires a user token with search:read.
Returns a list of message dicts with at least channel/ts/text/permalink.
"""
def _run_search_messages(query):
url = 'https://slack.com/api/search.messages'
query = f'from:@{username} after:{after_date}'

headers = {'Authorization': f'Bearer {USER_SLACK_TOKEN}'}

matches = []
Expand All @@ -293,6 +311,23 @@ def search_user_messages(username, after_date):
return matches


def search_user_messages(username, after_date, user_id=None):
"""Find messages from a given Slack user posted on or after `after_date` (YYYY-MM-DD).

Uses search.messages, which requires a user token with search:read.
Returns a list of message dicts with at least channel/ts/text/permalink.
"""
if user_id:
matches = _run_search_messages(f'from:<@{user_id}> after:{after_date}')
if matches or not username:
return matches

if not username:
return []

return _run_search_messages(f'from:@{username} after:{after_date}')


def get_user_and_message(event):
item = event['item']
channel = item['channel']
Expand Down
Loading