DEV Community

Nico Reyes
Nico Reyes

Posted on

Built a script to auto-archive old Slack messages. Company storage limit disappeared.

Built a script to archive old Slack messages automatically. Company storage limit disappeared.

Our workspace kept hitting the 10K message limit. Every month someone had to manually export conversations and delete stuff. Took 2 hours each time.

Figured there had to be a way to automate it.

Started Simple

Slack free tier caps at 10,000 messages. Once you hit it, old messages disappear unless you upgrade. Small team. Not worth paying $8 per person just for message history.

Manual process sucked:

  1. Export conversations as JSON
  2. Upload to Google Drive
  3. Delete messages from Slack
  4. Hope you remember where you saved everything

Took forever. People kept forgetting to do it.

What I Built

Python script that runs monthly. Connects to Slack API, grabs messages older than 90 days, saves them to markdown files, posts archive link to a channel, then deletes from Slack.

import os
from slack_sdk import WebClient
from datetime import datetime, timedelta

slack_token = os.getenv('SLACK_BOT_TOKEN')
client = WebClient(token=slack_token)

# Get messages older than 90 days
cutoff = (datetime.now() - timedelta(days=90)).timestamp()

channels = client.conversations_list()['channels']
for channel in channels:
    channel_id = channel['id']

    # Fetch old messages
    messages = client.conversations_history(
        channel=channel_id,
        oldest='0',
        latest=str(cutoff)
    )['messages']

    if not messages:
        continue

    # Save to markdown
    filename = f"archive/{channel['name']}_{datetime.now().strftime('%Y%m')}.md"
    with open(filename, 'w') as f:
        for msg in reversed(messages):
            timestamp = datetime.fromtimestamp(float(msg['ts']))
            user = msg.get('user', 'unknown')
            text = msg.get('text', '')
            f.write(f"**{timestamp}** - {user}: {text}\n\n")

    # Delete from Slack (requires additional perms)
    for msg in messages:
        client.chat_delete(channel=channel_id, ts=msg['ts'])

    print(f"Archived {len(messages)} messages from #{channel['name']}")
Enter fullscreen mode Exit fullscreen mode

What Actually Happened

First run archived 3,200 messages. Freed up like 30% of our storage immediately.

Runs automatically now via cron on the 1st of each month. Nobody has to think about it.

Slack API rate limits kicked in when deleting messages tho. Had to add sleep delays between batches.

Takes about 15 minutes to process everything now instead of instant.

Also realized archived messages are harder to search than I thought. Markdown files sit in Drive but nobody actually looks at them. Might add search later. Not sure if worth it honestly.

Setting It Up

You need Slack Bot Token with the right scopes. Python 3.8+. The slack_sdk library.

Store token in environment variable. I almost pushed credentials to GitHub once. Don't do that.

Code is pretty basic. No error handling for API failures or anything. Works for my use case tho.

Top comments (0)