LoginSignup
15
13

More than 5 years have passed since last update.

Slackのメッセージを一括削除するPythonコード

Posted at

Slackの一括削除機能が昔はあったそうですが今探すとarchiveページ自体消滅していたようで、
仕方ないのでAPIですぐできそうだったのでささっと書きました。(python2.7であまりに雑なコードですが)
generalはチャンネルごと作り直せないので掃除したいときなどに需要あるかもしれないのでここに置いておきます。
少しいじれば特定の人のメッセージだけ消すなどもできると思います。

トークンはこちらから取得してください
https://api.slack.com/custom-integrations/legacy-tokens

チャンネルIDはここに必要な情報を入れると見れます(general等チャンネル名とは違うので注意)
https://api.slack.com/methods/channels.info/test

Slackを見ながら実行するとどんどん消えていくのが見えて面白いです。(?)
当たり前ですが一旦消すと復旧はできませんので予めエクスポートするなど用法用量を守ってご利用ください。

delete_slack_message.py
#coding: utf-8

import urllib
import urllib2
import json
import time

delete_url = "https://slack.com/api/chat.delete"
hist_url = "https://slack.com/api/channels.history"
token = '[yourtoken]'
channel = '[channel_id]'

delete_params = {'token':token,
          'channel':channel
}
hist_params = {'token':token,
          'channel':channel,
          'count' : '1000',
}

hist_params = urllib.urlencode(hist_params)

req = urllib2.Request(hist_url)
req.add_header('Content-Type', 'application/x-www-form-urlencoded')
req.add_data(hist_params)

res = urllib2.urlopen(req)

body = res.read()
data = json.loads(body)


for m in data["messages"]:
  delete_params['ts'] = m["ts"]
  enc_params = urllib.urlencode(delete_params)

  req = urllib2.Request(delete_url)
  req.add_header('Content-Type', 'application/x-www-form-urlencoded')
  req.add_data(enc_params)


  res = urllib2.urlopen(req)

  body = res.read()
  print(body)
  #連続で送りすぎるとエラーになるので1秒待機
  time.sleep(1)                 
15
13
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
13