Recently, I shifted away from using Slack to a self-hosted version of Matrix paired with Riot. More on the reason for doing that and how it was done later, but as part of this migration was purging entire history of all channels in the Workspace on Slack.
I was hoping that Slack had some sort of functionality to bulk delete and/or wipe out entire history in a channel. Instead, it turned out the only way of doing so was the delete each message individually, one by one. Awesome.
That led me to search for a faster way of bulk deleting messages. Interestingly there was a Google Chrome extension called Message deleter for Slack which did automate messages deletion to some extent. There were a couple of downsides to this,
- The chat history needed to be loaded for it to work (assumingly because it used the
timestampsfrom the page)
- Each user had to install the extension and wait for it to finish!
For the latter point, the extension has an 'admin' version but I wasn't really interested in investing in that knowing that an API existed for Slack. Moving past the extension, I decided to put a stop to googling around and look into piecing together a quick, dirty script which would do the work. A quick glance at Slack API's, doodling around with some of them in terminal, and coming across a python client, I came up with a crude python script which,
- Pulls entire channel history
- Deletes each message one by one
Following is the code,
from slackclient import SlackClient import json import time slack_token = "<SLACK LEGACY TOKEN GOES HERE>" slack_channel_id = "<SLACK CHANNEL ID GOES HERE>" sc = SlackClient(slack_token) res = sc.api_call("conversations.history", channel=slack_channel_id, limit=1000) while res['has_more']: for message in res['messages']: time.sleep(1) status = sc.api_call("chat.delete", channel=slack_channel_id, ts=message['ts']) print(status) res = sc.api_call("conversations.history", channel=slack_channel_id, limit=1000) for message in res['messages']: time.sleep(1) status = sc.api_call("chat.delete", channel=slack_channel_id, ts=message['ts']) print(status)
Before using the script, make sure you have
slackclient python packages installed and are running
Python 2.7.14 (not tested on for any other version).
The way this script works is quite simple, it calls the
conversations.history and gets messages in batches of
1000. The batch is determined by the presence of
has_more in response. Each batch is then processed where in each message is that batch is deleted using
chat.delete api. The status of message deletion is printed out in terminal. Additionally, there is a delay of 1 second between message deletion to avoid hitting Slack's rate limiting.
The last loop you're seeing is in case the total messages are less than 1000.