There will be future post about creating simple slack bots in python and this quick post is kind of related ;)
Case is quite simple, we have a bot and it produced lot of crap on several channels. Here is a simple python snippet to find and delete messages.
# -*- coding: utf-8 -*-
#!/usr/bin/python
import time
from datetime import datetime, date, time
from slackclient import SlackClient
test_chan = "development"
SLACK_TOKEN = os.getenv("SLACK_TOKEN")
slack_client = SlackClient(SLACK_TOKEN)
def get_chan_id(channel_name):
"""Get channel id"""
channels = slack_client.api_call("channels.list")
channel_id = None
for channel in channels['channels']:
if channel['name'] == channel_name:
channel_id = channel['id']
if channel_id == None:
raise Exception("cannot find channel " + channel_name)
return channel_id
def find_and_delete(start, stop, chan):
"""Find and delete messages for user"""
oldest = (time.mktime(datetime.strptime(start, '%Y-%m-%d %H:%M:%S').timetuple()))
latest = (time.mktime(datetime.strptime(stop, '%Y-%m-%d %H:%M:%S').timetuple()))
history = slack_client.api_call("channels.history", channel=get_chan_id(chan), oldest=oldest, latest=latest)
x = 0
for i in history['messages']:
x = x + 1
if i['username'] == 'username':
status = slack_client.api_call("chat.delete", channel=get_chan_id(chan), ts=i['ts'])
print("Run: {}").format(x)
time.sleep(5)
if __name__ == "__main__":
find_and_delete("2019-10-26 06:00:00", "2019-10-26 08:40:00", test_chan)
Remember about slack api rate limits!
Rate Limits
Learn how to build bot users, send notifications, and interact with workspaces using our APIs.
