program story

채널의 모든 메시지 (~ 8K)를 Slack 정리

inputbox 2020. 11. 8. 09:53
반응형

채널의 모든 메시지 (~ 8K)를 Slack 정리


현재 Jenkins 통합에서 제공되는 ~ 8K 메시지가 포함 된 Slack 채널이 있습니다. 해당 채널에서 모든 메시지를 삭제하는 프로그래밍 방식이 있습니까? 웹 인터페이스는 한 번에 100 개의 메시지 만 삭제할 수 있습니다.


: 누군가가 이미 도우미 만들어 거기에서 나는 빨리 발견 여유 클리너를 이를 위해.

그리고 나를 위해 그것은 단지 :

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


기본 정리 명령이 작동하지 않아 다음 오류가 발생했습니다.

$ 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 

모든 메시지를 정리합니다.

HTTP 429 Too Many Requests슬랙 API 속도 제한으로 인한 오류 를 피하기 위해 1 초의 속도 제한을 사용합니다. 두 경우 모두 채널 이름이 #부호 없이 제공되었습니다.


공개 / 비공개 채널 및 채팅에서 메시지를 삭제하는 간단한 노드 스크립트를 작성했습니다. 수정하여 사용할 수 있습니다.

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

먼저 스크립트 구성 섹션에서 토큰을 수정 한 다음 스크립트를 실행합니다.

node ./delete-slack-messages CHANNEL_ID

다음 URL에서 토큰을 배울 수 있습니다.

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

또한 채널 ID는 브라우저 URL 표시 줄에 기록됩니다.

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


!!최신 정보!!

@ niels-van-reijmersdal이 의견에 언급했듯이.

이 기능은 제거되었습니다. 자세한 정보는이 스레드를 참조하십시오 : twitter.com/slackhq/status/467182697979588608?lang=en

!! 업데이트 종료 !!

여기에 트위터의 SlackHQ의 좋은 답변이 있으며 제 3 자 없이도 작동합니다. https://twitter.com/slackhq/status/467182697979588608?lang=ko

특정 채널 의 아카이브 ( http://my.slack.com/archives ) 페이지를 통해 대량 삭제할 수 있습니다 . 메뉴에서 "메시지 삭제"를 찾으십시오.


프로그래밍 방식으로 수행 할 필요가없는 다른 사용자를위한 빠른 방법은 다음과 같습니다.

(유료 사용자에게만 해당)

  1. 웹 또는 데스크톱 앱에서 채널을 열고 톱니 바퀴 (오른쪽 상단)를 클릭합니다.
  2. 보관 메뉴를 표시하려면 "추가 옵션 ..."을 선택하십시오. 메모
  3. "채널 메시지 보존 정책 설정"을 선택합니다.
  4. "특정 일 수 동안 모든 메시지 보관"을 설정합니다.
  5. 이 시간보다 오래된 모든 메시지는 영구적으로 삭제됩니다!

일반적으로이 옵션을 "1 일"로 설정하여 일부 컨텍스트와 함께 채널을 떠난 다음 위의 설정으로 돌아가서 보존 정책을 다시 "기본값" 으로 설정 하여 지금부터 계속 저장합니다.

참고 :
Luke는 다음과 같이 지적합니다. 옵션이 숨겨진 경우 : 전역 작업 영역 관리 설정, 메시지 보존 및 삭제로 이동하여 "작업 영역 구성원이이 설정을 재정의하도록 허용"을 선택해야합니다.


옵션 1 1 일 후 자동으로 메시지를 삭제하도록 Slack 채널을 설정할 수 있지만 약간 숨겨져 있습니다. 먼저 Slack 작업 공간 설정, 메시지 보존 및 삭제로 이동하여 "작업 공간 구성원이이 설정을 재정의하도록 허용"을 선택해야합니다. 그런 다음 Slack 클라이언트에서 채널을 열고 기어를 클릭 한 다음 "메시지 보관 수정 ..."을 클릭합니다.

옵션 2 다른 사람들이 언급 한 slack-cleaner 명령 줄 도구.

옵션 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.")

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


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


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.


If you like Python and have obtained a legacy API token from the slack api, you can delete all private messages you sent to a user with the following:

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()

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

참고URL : https://stackoverflow.com/questions/32824336/slack-clean-all-messages-8k-in-a-channel

반응형