Slack clean all messages (~8K) in a channel

后端 未结 11 547
暖寄归人
暖寄归人 2021-01-30 06:00

We currently have a Slack channel with ~8K messages all comes from Jenkins integration. Is there any programmatic way to delete all messages from that channel? The web interface

相关标签:
11条回答
  • 2021-01-30 06:51

    As other answers allude, Slack's rate limits make this tricky - the rate limit is relatively low for their chat.delete API at ~50 requests per minute.

    The best strategy that respects the rate limit is to retrieve messages from the channel you want to clear, then delete the messages in batches under 50 that run on a minutely interval.

    I've built a project containing an example of this batching that you can easily fork and deploy on Autocode - it lets you clear a channel via slash command (and allows you restrict access to the command to just certain users of course!). When you run /cmd clear in a channel, it marks that channel for clearing and runs the following code every minute until it deletes all the messages in the channel:

    console.log(`About to clear ${messages.length} messages from #${channel.name}...`);
    
    let deletionResults = await async.mapLimit(messages, 2, async (message) => {
      try {
        await lib.slack.messages['@0.6.1'].destroy({
          id: clearedChannelId,
          ts: message.ts,
          as_user: true
        });
        return {
          successful: true
        };
      } catch (e) {
        return {
          successful: false,
          retryable: e.message && e.message.indexOf('ratelimited') !== -1
        };
      }
    });
    

    You can view the full code and a guide to deploying your own version here: https://autocode.com/src/jacoblee/slack-clear-messages/

    0 讨论(0)
  • 2021-01-30 06:52

    !!UPDATE!!

    as @niels-van-reijmersdal metioned in comment.

    This feature has been removed. See this thread for more info: twitter.com/slackhq/status/467182697979588608?lang=en

    !!END UPDATE!!

    Here is a nice answer from SlackHQ in twitter, and it works without any third party stuff. https://twitter.com/slackhq/status/467182697979588608?lang=en

    You can bulk delete via the archives (http://my.slack.com/archives ) page for a particular channel: look for "delete messages" in menu

    0 讨论(0)
  • 2021-01-30 06:52

    Tip: if you gonna use the slack cleaner https://github.com/kfei/slack-cleaner

    You will need to generate a token: https://api.slack.com/custom-integrations/legacy-tokens

    0 讨论(0)
  • 2021-01-30 06:58

    Option 1 You can set a Slack channel to automatically delete messages after 1 day, but it's a little hidden. First, you have to go to your Slack Workspace Settings, Message Retention & Deletion, and check "Let workspace members override these settings". After that, in the Slack client you can open a channel, click the gear, and click "Edit message retention..."

    Option 2 The slack-cleaner command line tool that others have mentioned.

    Option 3 Below is a little Python script that I use to clear Private channels. Can be a good starting point if you want more programmatic control of deletion. Unfortunately Slack has no bulk-delete API, and they rate-limit the individual delete to 50 per minute, so it unavoidably takes a long time.

    # -*- coding: utf-8 -*-
    """
    Requirement: pip install slackclient
    """
    import multiprocessing.dummy, ctypes, time, traceback, datetime
    from slackclient import SlackClient
    legacy_token = raw_input("Enter token of an admin user. Get it from https://api.slack.com/custom-integrations/legacy-tokens >> ")
    slack_client = SlackClient(legacy_token)
    
    
    name_to_id = dict()
    res = slack_client.api_call(
      "groups.list", # groups are private channels, conversations are public channels. Different API.
      exclude_members=True, 
      )
    print ("Private channels:")
    for c in res['groups']:
        print(c['name'])
        name_to_id[c['name']] = c['id']
    
    channel = raw_input("Enter channel name to clear >> ").strip("#")
    channel_id = name_to_id[channel]
    
    pool=multiprocessing.dummy.Pool(4) #slack rate-limits the API, so not much benefit to more threads.
    count = multiprocessing.dummy.Value(ctypes.c_int,0)
    def _delete_message(message):
        try:
            success = False
            while not success:
                res= slack_client.api_call(
                      "chat.delete",
                      channel=channel_id,
                      ts=message['ts']
                    )
                success = res['ok']
                if not success:
                    if res.get('error')=='ratelimited':
    #                    print res
                        time.sleep(float(res['headers']['Retry-After']))
                    else:
                        raise Exception("got error: %s"%(str(res.get('error'))))
            count.value += 1
            if count.value % 50==0:
                print(count.value)
        except:
            traceback.print_exc()
    
    retries = 3
    hours_in_past = int(raw_input("How many hours in the past should messages be kept? Enter 0 to delete them all. >> "))
    latest_timestamp = ((datetime.datetime.utcnow()-datetime.timedelta(hours=hours_in_past)) - datetime.datetime(1970,1,1)).total_seconds()
    print("deleting messages...")
    while retries > 0:
        #see https://api.slack.com/methods/conversations.history
        res = slack_client.api_call(
          "groups.history",
          channel=channel_id,
          count=1000,
          latest=latest_timestamp,)#important to do paging. Otherwise Slack returns a lot of already-deleted messages.
        if res['messages']:
            latest_timestamp = min(float(m['ts']) for m in res['messages'])
        print datetime.datetime.utcfromtimestamp(float(latest_timestamp)).strftime("%r %d-%b-%Y")
    
        pool.map(_delete_message, res['messages'])
        if not res["has_more"]: #Slack API seems to lie about this sometimes
            print ("No data. Sleeping...")
            time.sleep(1.0)
            retries -= 1
        else:
            retries=10
    
    print("Done.")
    

    Note, that script will need modification to list & clear public channels. The API methods for those are channels.* instead of groups.*

    0 讨论(0)
  • 2021-01-30 06:59

    Here is a great chrome extension to bulk delete your slack channel/group/im messages - https://slackext.com/deleter , where you can filter the messages by star, time range, or users. BTW, it also supports load all messages in recent version, then you can load your ~8k messages as you need.

    0 讨论(0)
提交回复
热议问题