Skip to content

Instantly share code, notes, and snippets.

@thsunkid
Last active June 4, 2023 11:26
Show Gist options
  • Save thsunkid/fe9f373427441d3d0b72bbb38a23e745 to your computer and use it in GitHub Desktop.
Save thsunkid/fe9f373427441d3d0b72bbb38a23e745 to your computer and use it in GitHub Desktop.
Slack Channel Archiver Script
import datetime
from slack_sdk import WebClient
"""Get the SLACK_API_TOKEN:
1. To get a token for this script, create an app at https://api.slack.com/apps (Choose 'From scratch')
2. Go to 'OAuth & Permissions' > 'Scopes' section > 'User Token Scopes' > Add these permissions:
# admin.conversations:write
# admin.conversations:read
# channels:read
# channels:history
3. In that page, find and select "Install to your workspace"
4. Get the "User OAuth Token" and fill it below
"""
# Params
SLACK_API_TOKEN = "<your admin slack api token>"
ARCHIVE_LAST_MESSAGE_AGE_DAYS = 90
PERMANANT_CHANNELS = {'general', 'random'}
ARCHIVE_CHANNELS_IM_NOT_A_MEMBER_OF = False
oldest_message_time_to_prevent_archive = (
datetime.datetime.now() - datetime.timedelta(days=ARCHIVE_LAST_MESSAGE_AGE_DAYS)
).timestamp()
client = WebClient(SLACK_API_TOKEN)
my_user_id = client.auth_test()["user_id"]
def channel_has_recent_messages(channel_id):
# Getting up to 2 messages younger than ARCHIVE_LAST_MESSAGE_AGE_DAYS
response = client.conversations_history(
channel=channel_id,
oldest=oldest_message_time_to_prevent_archive,
limit=2
)
# Filter out message about our bot joining this channel
real_messages = list(filter(lambda m: m.get("user","") != my_user_id, response["messages"]))
# If we found at least one - return True, if not - False
return len(real_messages) > 0
next_cursor = None
while True:
response = client.conversations_list(exclude_archived=True, limit=200)
for channel in response["channels"]:
if channel["name"] in PERMANANT_CHANNELS:
continue
if not channel["is_member"] and not ARCHIVE_CHANNELS_IM_NOT_A_MEMBER_OF:
continue
if channel_has_recent_messages(channel["id"]):
print(f"#{channel['name']}: has recent messages")
else:
print(f"#{channel['name']}: archiving")
client.admin_conversations_rename(channel_id=channel["id"], name=f"archive-{channel['name']}")
client.admin_conversations_archive(channel_id=channel["id"])
if response.get("response_metadata") and response["response_metadata"].get("next_cursor"):
next_cursor = response["response_metatadata"]["next_cursor"]
else:
print("Reached the end of channels.")
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment