Cleaning messages from Slack automatically

Categories Uncategorized , , ,

Slack is a common item in our toolbelts these days, and the free tier makes it accessible to just about every project.

It has an extensive archive ability that can be useful for channels with human-sourced content. However, if you’re lucky enough to have some bots/automata to converse with, sometimes the chat logs are more like a panegyric for .bash_history that would surely make Hal2000 laugh maniacally from the ether.

How to purge old Slack messages

The following Ruby snippet can accomplishing this. I run it as part of a Lita-Bot plugin already integrated with Slack, but cron or manual invocations would work. It imposes a time-based cutoff for filtering messages, but can be adapted to selectively pick out messages, especially if you have a mixed-use channel.

If you want to go further down the rabbit hole of selecting messages, I’d recommended installing Pry and trying require 'pry'; binding.pry in the message loop, to quickly figure out how the criteria you’re interested in are serialized across the Slack API.

# gem install slack-api

require 'slack'

::Slack.configure do |slack|
  slack.token = 'xoxp-private-slack-token'  #TODO insert your token
@slack =

def slack_clean_channel(channel_name)
  channel_id = nil

  channels = @slack.channels_list
  raise 'Failed to list Slack rooms.' unless channels['ok']

  channels['channels'].each do |c|
    if c['name'] == channel_name
      channel_id = c['id']
  raise 'Failed to clean unknown room.' unless channel_id

  max_age = 48*60*60  # in seconds
  history = @slack.channels_history(channel: channel_id, latest:
  raise 'Failed to clean unknown room.' unless history['ok']

  history['messages'].each do |m|
                            ts: m['ts'],
                            channel: channel_id

Looking for a way to keep track of scheduled jobs? Check out the Cronbox command-line tool.