Skip to content

Instantly share code, notes, and snippets.

@kcemenike
Created March 5, 2022 10:23
Show Gist options
  • Save kcemenike/6f4674f5e4105c279fd3380811c7eefc to your computer and use it in GitHub Desktop.
Save kcemenike/6f4674f5e4105c279fd3380811c7eefc to your computer and use it in GitHub Desktop.
slackDeclutter
from slack_sdk import WebClient
from datetime import datetime, timedelta, timezone
# from IPython.display import clear_output
import time, pytz, re
USER_TOKEN = "xoxp-....." # Enter your user token here
PERIOD_AGO = 1 # How many hours/minutes/seconds 'ago' do you want to delete?
CHANNEL_NAME = 'upwork-jobs' # Change this to your channel name
SLEEP_TIME = 5 # Set this up with any number you wish, to prevent API throttling
client = WebClient(token=USER_TOKEN) # user_token hidden for seruciry
# Get Channel ID
for channel in client.conversations_list().data['channels']:
if channel['name'] == CHANNEL_NAME:
channel_id = channel['id']
# Delete 10,000 conversations backwards (200 x 50)
try:
for x in range(50):
res = client.conversations_history(
channel=channel_id, limit=200,
oldest = 0,
latest=str(
(datetime.now(tz=pytz.timezone('Africa/Lagos')) - timedelta(hours=PERIOD_AGO)).timestamp()))
# you can change the hours argument to minutes, or seconds, depending on your need
# Also change the timezone to anything you need
# A list of timezones is available if you run pytz.all_timezones or pytz.common_timezones
if len(res.data['messages'])==0: # exit if there are no more messages
print('All data deleted')
break
for n, message in enumerate(res.data['messages'][::-1]): # reverse message order: select from earliest
# Uncomment lines 3, 34, 35, 36, 39 and 40, if you're using IPython and want more verbose output
# print(f"link: {re.search('<(.*)?source', message['text']).group(1)[:-1]}")
# if n % 20 == 0:
# clear_output(wait=True)
client.chat_delete(channel=channel_id, ts=message['ts'])
time.sleep(SLEEP_TIME)
# clear_output(wait=True)
# print(f"Part {x}")
except (IndexError, OSError) as err:
print(err)
@kcemenike
Copy link
Author

Guide for this gist is here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment