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

问题描述 投票:67回答:10

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

slack-api slack
10个回答
61
投票

我很快发现有人已经帮助了这个问题:slack-cleaner

对我而言,它只是:

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


-2
投票
slack-cleaner --token=<TOKEN> --message --channel jenkins --user "*"

17
投票

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 

清除所有消息。

我使用1秒的速率限制来避免HTTP 429 Too Many Requests错误,因为松弛的api速率限制。在这两种情况下,通道名称都是在没有#标志的情况下提供的


15
投票

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

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/


12
投票

!! UPDATE!

如果@ niels-van-reijmersdal在评论中提到。

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

!!结束更新!!

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

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


8
投票

对于其他不需要编程的人来说,这是一个快速的方法:

(可能仅限付费用户)

  1. 在Web或桌面应用程序中打开频道,然后单击齿轮(右上角)。
  2. 选择“其他选项...”以显示存档菜单。笔记
  3. 选择“设置频道消息保留策略”。
  4. 设置“保留特定天数的所有邮件”。
  5. 超过此时间的所有邮件将被永久删除!

我通常将此选项设置为“1天”以使通道保留一些上下文,然后我返回上述设置,并将其保留策略设置回“默认”以继续从现在开始存储它们。

笔记: Luke指出:如果该选项被隐藏:您必须转到全局工作区管理员设置,消息保留和删除,并选中“让工作区成员覆盖这些设置”


4
投票

选项1您可以将Slack通道设置为在1天后自动删除消息,但它有点隐藏。首先,您必须转到Slack工作区设置,消息保留和删除,并选中“让工作区成员覆盖这些设置”。之后,在Slack客户端中,您可以打开频道,单击齿轮,然后单击“编辑邮件保留...”

选项2其他人提到的松弛清洁命令行工具。

选项3下面是一个用于清除私有频道的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.")

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


1
投票

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

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


0
投票

这是一个很棒的镀铬扩展程序,用于批量删除您的松弛频道/组/即时消息 - 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()
© www.soinside.com 2019 - 2024. All rights reserved.