首页 文章

Slack清除通道中的所有消息(~8K)

提问于
浏览
66

我们目前有一个Slack通道,大约8K消息都来自Jenkins集成 . 是否有任何编程方式删除该 Channels 的所有邮件? Web界面一次只能删除100条消息 .

10 回答

  • 15

    我很快发现有人已经帮忙了:slack-cleaner为此 .

    对我而言,它只是:

    slack-cleaner --token=<TOKEN> --message --channel jenkins --user "*" --perform

  • 4

    default clean命令对我没有用,给出以下错误:

    $ slack-cleaner --token=<TOKEN> --message --channel <CHANNEL>
    
    Running slack-cleaner v0.2.4
    Channel, direct message or private group not found
    

    但是后续工作没有任何问题来清理机器人消息

    slack-cleaner --token <TOKEN> --message --group <CHANNEL> --bot --perform --rate 1
    

    要么

    slack-cleaner --token <TOKEN> --message --group <CHANNEL> --user "*" --perform --rate 1
    

    清除所有消息 .

    由于松弛的api速率限制,我使用1秒的速率限制来避免 HTTP 429 Too Many Requests 错误 . 在这两种情况下,都提供了通道名称而没有 # 符号

  • 12

    我写了一个简单的节点脚本,用于删除来自公共/私人 Channels 和聊天的消息 . 您可以修改并使用它 .

    https://gist.github.com/firatkucuk/ee898bc919021da621689f5e47e7abac

    首先,在脚本配置部分修改您的令牌,然后运行脚本:

    node ./delete-slack-messages CHANNEL_ID
    

    您可以通过以下网址了解您的令牌:

    https://api.slack.com/custom-integrations/legacy-tokens

    此外,通道ID写在浏览器URL栏中 .

    https://mycompany.slack.com/messages/MY_CHANNEL_ID/

  • 1

    !!UPDATE!!

    正如@ niels-van-reijmersdal在评论中提到的那样 .

    此功能已被删除 . 有关详细信息,请参阅此主题:twitter.com/slackhq/status/467182697979588608?lang=en

    !!END UPDATE!!

    这是SlackHQ在Twitter上的一个很好的答案,它没有任何第三方的东西 . https://twitter.com/slackhq/status/467182697979588608?lang=en

    您可以通过特定 Channels 的档案(http://my.slack.com/archives)页面批量删除:在菜单中查找“删除消息”

  • 14

    对于其他没有't need to do it programmatic, here'的人 quick way

    (可能仅限付费用户)

    • 在Web或桌面应用程序中打开 Channels ,然后单击齿轮(右上角) .

    • 选择"Additional options..."以显示存档菜单 . notes

    • 选择"Set the channel message retention policy" .

    • 设置"Retain all messages for a specific number of days" .

    • 所有早于此时间的邮件将被永久删除!

    我通常将此选项设置为"1 day"以使通道保留一些上下文,然后我返回上面的设置,并且 set it's retention policy back to "default" 继续从现在开始存储它们 .

    Notes:
    Luke指出:如果该选项被隐藏:您必须转到全局工作区管理员设置,消息保留和删除,并检查"Let workspace members override these settings"

  • 0

    Option 1 您可以将Slack通道设置为在1天后自动删除消息,但它有点隐藏 . 首先,您必须转到Slack工作区设置,消息保留和删除,然后检查"Let workspace members override these settings" . 之后,在Slack客户端中,您可以打开一个 Channels ,单击齿轮,然后单击"Edit message retention..."

    Option 2 其他人提到的松弛清洁命令行工具 .

    Option 3 下面是一个用于清除私有 Channels 的Python脚本 . 如果您想要更多编程控制删除,可以是一个很好的起点 . 不幸的是,Slack没有批量删除API,他们将每个删除速率限制为每分钟50次,因此不可避免地需要很长时间 .

    # -*- 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.")
    

    请注意,该脚本需要修改才能列出并清除公共 Channels . 这些API方法是渠道 . *而不是组 . *

  • -1

    提示:如果你要使用松弛清洁剂https://github.com/kfei/slack-cleaner

    您需要生成一个令牌:https://api.slack.com/custom-integrations/legacy-tokens

  • 8

    这是一个很棒的Chrome扩展程序,用于批量删除您的松弛 Channels /群组/即时消息 - https://slackext.com/deleter,您可以按星号,时间范围或用户过滤消息 . 顺便说一句,它还支持加载最新版本的所有消息,然后您可以根据需要加载~8k消息 .

  • 0

    如果您喜欢Python并从slack api获得legacy API token,则可以使用以下内容删除发送给用户的所有私人消息:

    import requests
    import sys
    import time
    from json import loads
    
    # config - replace the bit between quotes with your "token"
    token = 'xoxp-854385385283-5438342854238520-513620305190-505dbc3e1c83b6729e198b52f128ad69'
    
    # replace 'Carl' with name of the person you were messaging
    dm_name = 'Carl'
    
    # helper methods
    api = 'https://slack.com/api/'
    suffix = 'token={0}&pretty=1'.format(token)
    
    def fetch(route, args=''):
      '''Make a GET request for data at `url` and return formatted JSON'''
      url = api + route + '?' + suffix + '&' + args
      return loads(requests.get(url).text)
    
    # find the user whose dm messages should be removed
    target_user = [i for i in fetch('users.list')['members'] if dm_name in i['real_name']]
    if not target_user:
      print(' ! your target user could not be found')
      sys.exit()
    
    # find the channel with messages to the target user
    channel = [i for i in fetch('im.list')['ims'] if i['user'] == target_user[0]['id']]
    if not channel:
      print(' ! your target channel could not be found')
      sys.exit()
    
    # fetch and delete all messages
    print(' * querying for channel', channel[0]['id'], 'with target user', target_user[0]['id'])
    args = 'channel=' + channel[0]['id'] + '&limit=100'
    result = fetch('conversations.history', args=args)
    messages = result['messages']
    print(' * has more:', result['has_more'], result.get('response_metadata', {}).get('next_cursor', ''))
    while result['has_more']:
      cursor = result['response_metadata']['next_cursor']
      result = fetch('conversations.history', args=args + '&cursor=' + cursor)
      messages += result['messages']
      print(' * next page has more:', result['has_more'])
    
    for idx, i in enumerate(messages):
      # tier 3 method rate limit: https://api.slack.com/methods/chat.delete
      # all rate limits: https://api.slack.com/docs/rate-limits#tiers
      time.sleep(1.05)
      result = fetch('chat.delete', args='channel={0}&ts={1}'.format(channel[0]['id'], i['ts']))
      print(' * deleted', idx+1, 'of', len(messages), 'messages', i['text'])
      if result.get('error', '') == 'ratelimited':
        print('\n ! sorry there have been too many requests. Please wait a little bit and try again.')
        sys.exit()
    
  • 59
    slack-cleaner --token=<TOKEN> --message --channel jenkins --user "*"
    

相关问题